i'm new to jquery.I'd like to know how to iterate form elements in reverse order in jquery using each()? Any help would be appreciated:)
Asked
Active
Viewed 3.1k times
24
-
7See [this question](http://stackoverflow.com/questions/1394020/jquery-each-backwards) – BoltClock Dec 21 '10 at 06:34
-
1@BoltClock. Then why didn't you close it (two years ago?) – gdoron Apr 30 '12 at 20:10
5 Answers
39
try this
$($("input").get().reverse()).each(function() { /* ... */ });

Bhanu Prakash Pandey
- 3,805
- 1
- 24
- 16
20
$($("input").get().reverse()).each(function() {
//function body here
});
The .get().reverse()
returns the reversed array of all your elements
You can then use each()
to return each individual element.
Hope this helps.
-
1Welcome to the site, to format your code blocks simply indent each line by four spaces. See http://stackoverflow.com/editing-help for more. – BoltClock Dec 21 '10 at 06:38
-
12
I use a similar method as above, but shorter, define a jQuery reverse function to be the same as the reverse function of an array:
$.fn.reverse = [].reverse;
now you can use it like this:
$('img').reverse().each(function(){ /* do something */ });

Willem
- 5,364
- 2
- 23
- 44
-
This works in every case where I had to use this, but does anybody know why this isn't implemented in jQuery by default? – Willem Jan 03 '11 at 13:25
-
Well, this method is not required that often by developers. And jQuery has plugins support. If don't have something, create. – machineaddict Jul 16 '14 at 11:06
3
Better yet
$.each( $( $('input').get().reverse() ) , function(){ /* ... */ });

qwertymk
- 34,200
- 28
- 121
- 184
-
reverse is not a built-in jQuery command, your answer results in "TypeError: $(...).reverse is not a function" – efreed Oct 29 '15 at 17:57
3
I prefer creating a reverse plug-in eg
jQuery.fn.reverse = function(fn) {
var i = this.length;
while(i) {
i--;
fn.call(this[i], i, this[i])
}
};
Usage eg:
$('#product-panel > div').reverse(function(i, e) {
alert(i);
alert(e);
});

James Westgate
- 11,306
- 8
- 61
- 68