1

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?

2 Answers 2

14

I'd suggest:

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

JS Fiddle demo.

References:

Sign up to request clarification or add additional context in comments.

Comments

4

I think this may work too:

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

1 Comment

I'm having trouble visualising how that works...off to the docs for me! Also, welcome to Stack Overflow, and may I offer you your first +1? =)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.