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.0k 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 is supporting Monica Apr 30 '12 at 20:10
5 Answers
38
try this
$($("input").get().reverse()).each(function() { /* ... */ });
Bhanu Prakash Pandey
- 3,765
- 1
- 23
- 16
19
$($("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
-
11
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,361
- 2
- 22
- 43
-
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
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
- 10,989
- 7
- 61
- 67
2
Better yet
$.each( $( $('input').get().reverse() ) , function(){ /* ... */ });
qwertymk
- 32,454
- 27
- 117
- 182
-
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