24

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

illuminatus
  • 1,886
  • 3
  • 16
  • 19

5 Answers5

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.

BoltClock
  • 665,005
  • 155
  • 1,345
  • 1,328
Osiris
  • 4,127
  • 2
  • 18
  • 50
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