Link

Header here

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); 
+6
source share
4 answers

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 .

+8
source

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); }); }); 
+1
source

Try the following:

 $(document).ready(function() { $('.block').each(function() { var divtext = $('div.text', this) $('a.link', this).insertAfter(divText); }); }); 
+1
source

try it

 $('div.block a.link').each(function() { $(this).siblings('div.text').after(this); }); 
0
source

Source: https://habr.com/ru/post/893785/


All Articles