Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery .each() backwards

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?

like image 614
Jack Mills Avatar asked Sep 08 '09 13:09

Jack Mills


2 Answers

$($("li").get().reverse()).each(function() { /* ... */ }); 
like image 73
Joe Chung Avatar answered Sep 17 '22 18:09

Joe Chung


I present you with the cleanest way ever, in the form of the world's smallest jquery plugin:

jQuery.fn.reverse = [].reverse; 

Usage:

$('jquery-selectors-go-here').reverse().each(function () {     //business as usual goes here }); 

-All credit to Michael Geary in his post here: http://www.mail-archive.com/[email protected]/msg04261.html

like image 26
Waldo Hampton Avatar answered Sep 16 '22 18:09

Waldo Hampton