Is there an inbuilt way to use JQuery's .each() in reverse?

Go To


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()

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.

2012-04-03 23:53
by Marty - Jon Friskics 2012-04-03 23:56
@JonFriskics That'll work, thanks - voting to close my question : - Marty 2012-04-03 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 2012-04-03 23:57
underscore.js - keystorm 2012-04-04 00:04


Use this

$($("#nav a").get().reverse()).each(function() { 
2012-04-03 23:59
by Starx


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 :)

2012-04-03 23:59
by Darragh Enright