Reputation: 57
I need to get an existing URL from an href and repeat it with some extra characters in between (in order to trigger a popup).
For example
<div class="item"><a href="https://website.com"></a></div>
Would become <div class="item"><a href="https://website.com?modal-link=https://website.com"></a></div>
I'm pretty sure I'm getting the terminology incorrect and therefore my searches are not getting results for what I'm trying to achieve!
Thanks in advance :)
Upvotes: 0
Views: 207
Reputation: 50854
You can select all anchor tags (<a>
) on in your div with the class item
using $('.item a')
and then loop over each using .each
. When looking at a specific anchor tag you can get it's current href
by using $(this).attr("href")
and then modify it to have the link added to the end of it.
Lastly, you can update the current anchor tag by using $(this).attr('href', href);
See working example below:
$('.item a').each(function() {
let href = $(this).attr('href'); // get href from the anchor tag
href += "?modal-link=" + href; // add the query string to it
$(this).attr('href', href); // update the href attribute
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="https://website.com">My Link (same)</a>
<div class="item">
<a href="https://website.com">My Link (changes)</a>
<br/>
<a href="https://website2.com">My Link2 (changes)</a>
</div>
Upvotes: 1