3

I have this code from earlier question

$("div").each(function(i) {
    $(this).find("span").text(++i);
}); 

-- full code in action = http://jsfiddle.net/pm3YL/

This JQuery code count every div in the page and add the order number inside span

But I need to do the same descending order

So the output will be like this one

http://jsfiddle.net/pm3YL/1/

Instead of

http://jsfiddle.net/pm3YL/

Community
  • 1
  • 1
Jim
  • 1,430
  • 5
  • 18
  • 41

4 Answers4

6

You can use this:

$($("div").get().reverse()).each(function (i) {
    $(this).find("span").text(++i);
});

Demo here

Another way, using also jQuery with reverse is:

$.fn.reverse = [].reverse;
$("div").reverse().each(function (i) {
    $(this).find("span").text(++i);
});

This demo here. (Thank you Ian for the suggestion.)

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 = $("div").length;
$("div").each(function (i) {
    $(this).find("span").text(nr_of_divs - i);
});

This demo here

One more, kind of related to the one above and inspired by Adeneo's answer:

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

Demo here

Community
  • 1
  • 1
Sergio
  • 28,539
  • 11
  • 85
  • 132
  • Another option for reversing is using this: `jQuery.fn.reverse = [].reverse;`, and then just `$("div").reverse().each(func...`. Taken from here: http://stackoverflow.com/questions/1394020/jquery-each-backwards – Ian Aug 17 '13 at 18:51
  • 1
    Good suggestion @Ian! added it to the answer. – Sergio Aug 17 '13 at 19:01
3

You can put something like :

var length_div = $("div").length

    $("div").each(function(i) {
        var tmp  = length_div-i;   
        $(this).find("span").text(tmp);
    });
epsilones
  • 11,279
  • 21
  • 61
  • 85
  • You might want to store `$("div")` *outside* of the `.each()` loop, so that it isn't executed every iteration – Ian Aug 17 '13 at 18:49
  • @Ian absolutely right and I could also not use the tmp variable, but so it is more clear for Jim – epsilones Aug 17 '13 at 19:01
  • Yeah, the `tmp` variable is fine, I just meant that running `$("div")` once will only query the DOM once, which probably is the most expensive part of most of these operations. Anyways, good example :) – Ian Aug 17 '13 at 19:08
3
$("div span").text(function(i) {
    return $("div span").length-i;
});

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
2

You could write a for-loop that runs in reverse through the collection, but I guess it's simpler to just subtract the counter from the number of elements to get a reverse numbering:

var divs = $("div"),
    l = divs.length;
divs.each(function(i) {
    $(this).find("span").text(l - i);
});

(Demo)

Bergi
  • 630,263
  • 148
  • 957
  • 1,375