insertAfter within a loop
Asked Answered
C

4

7

I have some code generated by a 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 to after the text div. I have tried this:

$(document).ready(function() {
        $('.block').each(function() {
            $('.block a.link').insertAfter('.block div.text');                      
        });
    });

but this only results in links being repeated about 10 times (the number of times looped.

I tried using $(this) but I don't quite understand how to write the correct syntax to append the a.link within the function... like this:

 $(this).a.link.insertAfter($(this).div.text);
Calesta answered 28/7, 2011 at 14:48 Comment(0)
T
8

Something like this should work, using siblings and after:

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

That says "for each element matched, find the element that matches .text and insert the original element after it".

Alternatively, you could do this:

$('.block a.link').each(function() {
    $(this).parent().append(this);
});

This presumes that you want to put the element at the end of the div.block.

Terrieterrier answered 28/7, 2011 at 14:53 Comment(1)
Thanks @Terrieterrier - I think putting it to the end of the block div is a better idea.Calesta
C
1

You could do (if you want it after the 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 class block)

$(document).ready(function() {
    $('.block a').each(function(){
       $(this).closest('div.block').after(this);
    });
   });
Comeaux answered 28/7, 2011 at 14:53 Comment(1)
Thanks @Nicola Peluchetti - I don't want it after the block, but it's good to know how to do this.Calesta
E
1

Try this:

$(document).ready(function() {
            $('.block').each(function() {
                var divtext = $('div.text', this)
                $('a.link', this).insertAfter(divText);
            });
});
Eleemosynary answered 28/7, 2011 at 14:53 Comment(1)
Thank @Cybernate - another method I didn't know.Calesta
T
0

Try this

$('div.block a.link').each(function() {
    $(this).siblings('div.text').after(this);
});
Tooth answered 28/7, 2011 at 14:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.