2

Possible Duplicate:
JQuery .each() backwards

What is the easiest way to use .each() in reverse? At the moment I am doing this:

var temp = [];

$("#nav a").each(function()
{
    temp.push($(this));
});

temp.reverse();
for(var i = 0; i < temp.length; i++)
{
    var a = temp[i];

    // Work with a.
}

It would be nice if I could do something like:

$("#nav a").reverse().each(function()
{
    // Work with $(this).

});

The context is that I have a collection of elements using float: right which displays them in reverse order and I want to iterate over them from left to right like normal.

Community
  • 1
  • 1
Marty
  • 39,033
  • 19
  • 93
  • 162
  • http://stackoverflow.com/questions/1394020/jquery-each-backwards – Jon Friskics Apr 03 '12 at 23:56
  • @JonFriskics That'll work, thanks - voting to close my question :) – Marty Apr 03 '12 at 23:57
  • Great question to which I believe the answer is "no". Some genius needs to do a small add-on package to jQuery to supply all the obvious functional programming primitives ... if there is one already somebody plz call me a dolt and name it :-) – Pointy Apr 03 '12 at 23:57
  • [underscore.js](http://documentcloud.github.com/underscore/) ? – keystorm Apr 04 '12 at 00:04

2 Answers2

7

Use this

$($("#nav a").get().reverse()).each(function() { 
     //..........
});
Starx
  • 77,474
  • 47
  • 185
  • 261
0

I can't take credit for this because I saw it somewhere else here on SO but I think this should help; add the functionality to jQuery's prototype like so:

$.fn.reverse = [].reverse

Then use it as indicated above:

$('#nav a').reverse(); // returns a reversed array of elements

Hope this helps :)

Darragh Enright
  • 13,676
  • 7
  • 41
  • 48