0

Is there any way to modify the order JQuery each() accesses the elements on the page?

I.e I have 4 elements on the page and I want element 3 to come first, then 2, then 4 and then 1.

Thanks

Richard

4 Answers 4

5

Assume you reorder images.

imgs = $( 'img' );

imgs.eq( 3 ).insertBefore( imgs.eq( 1 ) );

imgs.eq( 1 ).insertAfter( imgs.eq( 4 ) );

Should do the trick.

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

Comments

2

.each() will deliver the nodes the same way they appear in the DOM. But it also passes the index into the callback functions. So if you need to act differently, check the index

$('object').each(function(index) {
    if( index === 2)
        alert('yay');
});

Ref.: .each()

Comments

0

if you know that why not just reference them in that order without using each.

Comments

0
$items = $('.my-selector');
my_array = [ $items.get(2), $items.get(1), $items.get(3), $items.get(0) ];
jQuery.each(my_array, callback_function);

Note that the jQuery object is 0-indexed.

Comments

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.