Search code examples
jqueryeachdom-manipulationinsertafter

jQuery: Rearranging Elements Without Repeating


Let's say you have HTML like this:

<div class="section">
    <div class="bottom">bottom</div>
    <div class="top">top</div>
</div>
<div class="section">
    <div class="bottom">bottom</div>
    <div class="top">top</div>
</div>

and you want to move .top above .bottom in each .section with jQuery.

I'm trying to do this with:

$('.section').each(function (i, obj) {
    $('.bottom').insertAfter('.top');
});

But this is causing "bottom" to repeat itself four times in each section.

Fiddle: http://jsfiddle.net/TLejL/

What am I doing wrong?


Solution

  • Try to use the $(this) reference inside the .each() function,

    $('.section').each(function (i, obj) {
        $(this).find('.bottom').insertAfter($(this).find('.top'));
    });
    

    or

    $('.top').each(function() {
        $(this).closest('.section').prepend($(this));
    });
    

    DEMO