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?
You cannot iterate backwards with the jQuery each function, but you can still leverage jQuery syntax.
Try the following:
Needed to do a reverse on $.each so i used Vinay idea:
worked nicely, thanks
I think u need
Here are different options for this:
First: without jQuery:
Demo here
... and with jQuery:
You can use this:
Demo here
Another way, using also jQuery with reverse is:
This demo here.
One more alternative is to use the
length
(count of elements matching that selector) and go down from there using theindex
of each iteration. Then you can use this:This demo here
One more, kind of related to the one above:
Demo here
I recognize that jQuery supports and encourages plugins. That said, you may find this article relevant: Don’t modify objects you don’t own. In this case at least, I opted not to extend jQuery on the off chance that another plugin defines reverse differently.
Here's a simple solution that doesn't extend the jQuery object.