I have a number of repeating divs on a page and am trying to iterate through them, grab the text in 'contentBlock-heading', and finally append it to the existing href hyperlink. For each href, the end result should look as follows: 'community-chat/registration?ccdatedesc=Thursday, March 17 @ 7 pm CT | 8 pm ET:
<div >
<div >
<figure>
<img src="community-chat_620px.png" alt="alt text goes here">
</figure>
</div>
<div >
<h2 >Thursday, March 17 @ 7 pm CT | 8 pm ET</h2>
<p><strong>Register to join </strong><sup>®</sup><strong>.</strong></p>
<p><a href="community-chat/registration">Save My Spot</a></p>
</div>
</div>
I have tried the following:
<script type="text/javascript">
$( document ).ready(function() {
$('.contentBlock-content').each(function() {
var ccdatedesc = $(".contentBlock-heading").text();
$('.contentBlock-content a').attr('href', function(index, attr) {
return attr (attr.indexOf('?') >=0 ? '&ccdatedesc=' : '?') ccdatedesc;
});
});
});
</script>
This successfully appends the text to the href, but unfortunately appends ALL instances of text to each href:
href="community-chat/registration?&ccdatedesc=Thursday, March 17 @ 7 pm CT | 8 pm ETThursday, March 17 @ 7 pm CT | 8 pm ET&ccdatedesc=Thursday, March 17 @ 7 pm CT | 8 pm ETThursday, March 17 @ 7 pm CT | 8 pm ET">Save My Spot</a>
Can any help solve this for me?
CodePudding user response:
$( document ).ready(function() {
$('.contentBlock-content').each(function() {
var ccdatedesc = $(this).children(".contentBlock-heading").html();
$(this).find('a').attr('href', function(index, attr) {
return attr (attr.indexOf('?') >=0 ? '&ccdatedesc=' : '?') ccdatedesc;
});
});
});
as a quick note, you can't use whitespaces in urls so you actually need to url encode those strings first if you want this to actually work