InsertAfter inside the loop
I have the code generated by CMS:
<div class="block"> <a class="link" href="#">Link</a> <h4>Header here</h4> <div class="text">Some text here</div> </div> and I need to move the link after the text div. I tried this:
$(document).ready(function() { $('.block').each(function() { $('.block a.link').insertAfter('.block div.text'); }); }); but this only leads to the fact that the links are repeated about 10 times (the number of loops is looped.
I tried using $ (this), but I donβt quite understand how to write the correct syntax to add a.link to the function ... for example:
$(this).a.link.insertAfter($(this).div.text); Something like this should work using siblings and after :
$('.block a.link').each(function() { $(this).siblings('.text').after(this); }); This suggests that "for each element matches, find the element that matches the .text and insert the original element after it."
Alternatively, you can do this:
$('.block a.link').each(function() { $(this).parent().append(this); }); This assumes that you want to put the element at the end of div.block .
You could do it (if you want it after a div with class text):
$(document).ready(function() { $('.block a').each(function(){ $(this).next('div.text').after(this); }); }); or (if you want it after the div with the class)
$(document).ready(function() { $('.block a').each(function(){ $(this).closest('div.block').after(this); }); });