472

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?

John Slegers
  • 45,213
  • 22
  • 199
  • 169
Jack Mills
  • 6,022
  • 5
  • 34
  • 38

12 Answers12

727
$($("li").get().reverse()).each(function() { /* ... */ });
Joe Chung
  • 11,955
  • 1
  • 24
  • 33
  • 15
    Should be important to note that the index is not reversed, so if you are only wanting to do the last three, for instance, you cannot expect `
  • Item 5
  • ` to have an index of 0. – pathfinder Dec 10 '12 at 23:50
  • 8
    to David Andres: may be you forgot to add additional $() before li. I did this mistake and received "undefined func". – Michal - wereda-net Nov 19 '14 at 11:19
  • 2
    @DavidAndres: You missed the `.get()` which turns the jQuery wrapped array into an ordinary JS array. The JS array has `.reverse()`. – stackular Feb 09 '15 at 14:13
  • 2
    Caution: `Array.reverse()` both modifies the array **in place** and returns the reversed array. So this solution actually relies upon $().get() returning a new array, and _not_ a reference to some internal jQuery or DOM array. Probably a safe bet within the confines of this example. Caveat Coder. – Bob Stein Feb 13 '17 at 19:54