12

How can I reverse an order with jquery?

I tried with the suggestion like this but it won't work!

$($(".block-item").get().reverse()).each(function() { /* ... */ });

Have a look here.

I want the boxed to be rearranged like this,

18
17
16
etc

Thanks.

Run
  • 54,938
  • 169
  • 450
  • 748

5 Answers5

22

If you have a container around the list, it's a little easier:

$("#container").append($(".block-item").get().reverse());

http://jsfiddle.net/BhTEN/12/

Jamie Treworgy
  • 23,934
  • 8
  • 76
  • 119
11

You can use this:

$($(".block-item").get().reverse()).each(function (i) {
    $(this).text(++i);
});

Demo here.
Second demo here (changing the DOM elements positioning).

Another way, using also jQuery with reverse is:

$.fn.reverse = [].reverse;
$(".block-item").reverse().each(function (i) {
    $(this).text(++i);
});

This demo here.
Second demo here (changing the DOM elements positioning).

One more alternative is to use the length (count of elements matching that selector) and go down from there using the index of each iteration. Then you can use this:

var nr_of_divs = $(".block-item").length;
$(".block-item").each(function (i) {
    $(this).text(nr_of_divs - i);
});

This demo here
Second demo here (changing the DOM elements positioning).

One more, kind of related to the one above:

var nr_of_divs = $(".block-item").length;
$(".block-item").text(function (i) {
    return nr_of_divs - i;
});

Demo here

Sergio
  • 28,539
  • 11
  • 85
  • 132
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/129036/discussion-between-seika85-and-sergio). – Seika85 Nov 25 '16 at 12:32
5

Your code is working. Just choose jQuery framework on the left hand.

 $($(".block-item").get().reverse()).each(function() {
     $(this).appendTo($(this).parent());
 });
Farshid Zaker
  • 1,960
  • 2
  • 22
  • 39
2

Could this be what you are looking for?

http://plugins.jquery.com/project/reverseorder

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • yes it is. I thought there are other simpler methods than using this plugin. thanks though! – Run Jun 02 '11 at 19:14
1

try this:

function disp(divs) {
      var a = [];
      for (var i = 0; i < divs.length; i++) {
        a.push(divs[i].innerHTML);
      }
    alert(a);
    }

    disp( $("div.block-item").get().reverse() );

DEMO

xkeshav
  • 53,360
  • 44
  • 177
  • 245