dwinnbrown dwinnbrown - 9 days ago 7
HTML Question

Using $(this) within .each()

I have a series of elements laid out in HTML

I am trying to get the value of the

href
for each div with the class
wsite-com-category-product-wrap
and then use this to insert a new button with the same href.

My current code is inserting all the links (for items with the class
.wsite-com-category-product-wrap
) into themselves meaning that each element has about 10 links in now instead of just the one.

The code I have written to do this:



$(".wsite-com-category-product-wrap").each(function() {

var link = $(this).find("a").attr("href");
$("<a href=" + link + " class='custom-category-button'>Test</a>").insertAfter(".wsite-com-product-price");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="wsite-com-category-product-wrap">
<a href="#" class="link">Link content</a>
<div>more divs</div>
</div>




Answer

You can use a jquery object with .insertAfter, not just a string selector.

So, change this:

$("<a href=" + link + " class='custom-category-button'>Test</a>")
    .insertAfter(".wsite-com-product-price");

to:

$("<a href=" + link + " class='custom-category-button'>Test</a>")
    .insertAfter($(".wsite-com-product-price", this));