tags:

views:

2312

answers:

4

Hi, I'm using JQuery to select some elements on a page and then move them around in the DOM. The problem I'm having is I need to select all the elements in the reverse order that JQuery naturally wants to select them. For example:

<ul>
   <li>Item 1</li>
   <li>Item 2</li>
   <li>Item 3</li>
   <li>Item 4</li>
   <li>Item 5</li>
</ul>

I want to select all the li items and use the .each() command on them but I want to start with Item 5, then Item 4 etc. Is this possible?

Thanks

A: 

You cannot iterate backwards with the jQuery each function, but you can still leverage jQuery syntax.

Try the following:

//get an array of the matching DOM elements   
var liItems = $("ul#myUL li").get();

//iterate through this array in reverse order    
for(var i = liItems.length - 1; i >= 0; --i)
{
  //do Something
}
David Andres
+16  A: 
$($("li").get().reverse()).each(function() { /* ... */ });
Joe Chung
This doesn't work on my end, probably because the reverse function is undefined.
David Andres
Array.reverse has been around since JavaScript 1.1. Which browser are you using?
Joe Chung
Took a look at it again. Works fine.
David Andres
+11  A: 

You can do

jQuery.fn.reverse = function() {
    return this.pushStack(this.get().reverse(), arguments);
};

followed by

$(selector).reverse().each(...)
Vinay Sajip
Thanks Vinay, although the chosen answer works too, I much prefer yours.
Luke Duddridge
I love this too.
CallMeLaNN
A: 

Needed to do a reverse on $.each so i used Vinay idea:

//jQuery.each(collection, callback) =>
$.each($(collection).get().reverse(), callback func() {});

worked nicely, thanks

finklez