Reputation: 185
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
Upvotes: 0
Views: 4061
Reputation: 4820
Assume you reorder images.
imgs = $( 'img' );
imgs.eq( 3 ).insertBefore( imgs.eq( 1 ) );
imgs.eq( 1 ).insertAfter( imgs.eq( 4 ) );
Should do the trick.
Upvotes: 5
Reputation: 4749
$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.
Upvotes: 0
Reputation: 236022
.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()
Upvotes: 2
Reputation: 47290
if you know that why not just reference them in that order without using each
.
Upvotes: 0