Reputation: 25
I'm trying to wrap each element in an anchor tag, but I'm unsure of how to do it.
I tried to use .each to run a function, that uses .wrap to wrap the element.
Here's what i did:
<div class="product-icon-container">
<div class="product-icon product-share"><i class="fas fa-link"></i>Share</div>
<div class="product-icon product-heart"><i class="far fa-heart"></i>Save</div>
</div>
<input type="hidden" class="post-url" value="<?php the_permalink() ?>">`
var postUrl = $(".post-url").val()
$(".post-url").each(function(){
$(".product-share").wrap('a href="' + postUrl + '"></a>');
});
What happened was it wrapped all the elements as many times as the each function runs.
Upvotes: 1
Views: 182
Reputation: 27092
Sure, you call .wrap()
for each .post-url (for example 10 times), without specifying which elements you want to use (class returns a collection, not single element).
Not so strong in jQuery, but it should be st. like this:
$(".post-url").each(function(){
$(this).prev('.product-icon-container').find('.product-share').wrap('<a href="' + $(this).val() + '"></a>');
^^
});
In your postUrl
it's always the same value, you don't change it for each .post-url
element.
https://jsfiddle.net/rgdp9zLe/
Upvotes: 1