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?
I found
Array.prototype.reverse
unsuccessful with objects, so I made a new jQuery function to use as an alternative:jQuery.eachBack()
. It iterates through as the normaljQuery.each()
would, and stores each key into an array. It then reverses that array and performs the callback on the original array/object in the order of the reversed keys.You can do
followed by
You can also try
If you don't want to save method into jQuery.fn you can use
I present you with the cleanest way ever, in the form of the world's smallest jquery plugin:
Usage:
-All credit to Michael Geary in his post here: http://www.mail-archive.com/discuss@jquery.com/msg04261.html
I prefer creating a reverse plug-in eg
Usage eg: