jrutter
jrutter

Reputation: 3213

How to move multiple DOM elements using jQuery?

I have the following code:

<div class="product">
    <div class="description"></div>
    <div class="image"></div>
</div>

<div class="product">
    <div class="description"></div>
    <div class="image"></div>
</div>

<div class="product">
    <div class="description"></div>
    <div class="image"></div>
</div>

And Im trying to select all .image elements and move them before each .product element.

When I use the following command, it takes all the images and moves them before the first .product. Im stuck, I tried a foreach - that didnt seem to work.

$('.product').before($('.image'));

Any ideas?

Upvotes: 1

Views: 3436

Answers (2)

simo
simo

Reputation: 15478

I think this may work too:

$('.product').each(function (index) {
    $(this).before($('.image').eq(index));
});

Upvotes: 4

David Thomas
David Thomas

Reputation: 253308

I'd suggest:

$('.image').each(
    function(){
        $(this).insertBefore($(this).closest('.product'));
    });

JS Fiddle demo.

References:

Upvotes: 14

Related Questions