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,986
  • 4
  • 16
  • 19

5 Answers5

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.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Osiris
  • 4,195
  • 2
  • 22
  • 52
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