7

I need to iterate over jquery child elements in reverse:

$("#parent").children().each(function() {
  # do stuff
})

but in reverse.

I have seen the use of reverse() with get()

$($("li").get().reverse()).each(function() { /* ... */ });

but don't seem able to make it work with children().

user984003
  • 28,050
  • 64
  • 189
  • 285
  • 1
    possible duplicate of [JQuery .each() backwards](http://stackoverflow.com/questions/1394020/jquery-each-backwards) – Eric May 17 '13 at 13:13

5 Answers5

5

Using the same strategy as before:

$($("#parent").children().get().reverse()).each(function() {
      # do stuff
})

Or slightly more neatly:

[].reverse.call($("#parent").children()).each(function() {
      # do stuff
})
Eric
  • 95,302
  • 53
  • 242
  • 374
2

try this

jQuery.fn.reverse = [].reverse;

$("#parent").children().reverse().each(function () {
});

SEE HERE

PSR
  • 39,804
  • 41
  • 111
  • 151
  • Why would anybody downvote this? With the edit to add the step of copying the "reverse" method from the array prototype to the jQuery "fn" object, this should work just fine. – Pointy May 17 '13 at 13:15
  • Moreover, this is how jQuery itself does it (see e.g. `$.sort` in the sources). – georg May 17 '13 at 13:27
1

How about

$.each( $("#parent").children().get().reverse(), function(){
   // whatever..
} );

Demo at http://jsfiddle.net/mPsep/

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
0

This will work

$($("li").children().get().reverse()).each(function() { /* ... */ });

Demo: http://jsfiddle.net/tymeJV/maxzA/

tymeJV
  • 103,943
  • 14
  • 161
  • 157
0

Try This:SEE http://api.jquery.com/child-selector/

$($("#parent > li").get().reverse()).each(function() {
  # do stuff
})
Somnath Kharat
  • 3,570
  • 2
  • 27
  • 51