April 3, 2012

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

Question by Marty Wallace

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.

Answer by Starx

Use this

$($("#nav a").get().reverse()).each(function() { 
     //..........
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!