Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery: reverse an order

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.

like image 423
Run Avatar asked Jun 02 '11 19:06

Run


2 Answers

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

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

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

like image 107
Jamie Treworgy Avatar answered Oct 21 '22 04:10

Jamie Treworgy


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

like image 27
Sergio Avatar answered Oct 21 '22 05:10

Sergio