6

how i can make the ".each" to starts with the div id small number "1" to the big number "5" ... 1 / 2 / 3 / 4 / 5

lets say i have this divs

<div class="TID_5">TID 5</div>
<div class="TID_4">TID 4</div>
<div class="TID_3">TID 3</div>
<div class="TID_2">TID 2</div>
<div class="TID_1">TID 1</div>

i have this jquery what im using, but starts with the first div class id number "5" but i need to start with number 1 ...

$("div[class*='TID_']").each(function() {
 // code is come here ...
});
Kris Harper
  • 5,484
  • 8
  • 47
  • 91
Mihai Viteazu
  • 1,441
  • 3
  • 11
  • 13

4 Answers4

12

Try

$("div[class*='TID_']").sort(function(e1, e2){
    return $(e1).attr('class') > $(e2).attr('class')
}).each(function() {
    console.log($(this).text())
});

Demo: Fiddle

Sergio
  • 27,998
  • 10
  • 81
  • 130
Arun P Johny
  • 376,738
  • 64
  • 519
  • 520
  • @F4r-20 it was because the updated version was not set as the base.. fixed now – Arun P Johny Jul 30 '13 at 09:10
  • thanks works perfect ... but one question how i can find what is the biggest id number ? on my example is = 5 – Mihai Viteazu Jul 30 '13 at 09:18
  • @MihaiViteazu once teh list is sorted use `.last()` to get the last item the using `.attr('class')` get the class value, from that you can extract the value – Arun P Johny Jul 30 '13 at 09:35
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/34439/discussion-between-mihai-viteazu-and-arun-p-johny) – Mihai Viteazu Jul 30 '13 at 11:21
3

You can use index to reverse the elements.

Live Demo

elements = $("div[class*='TID_']")
elements.each(function(index) {
  current = elements.eq(elements.length - index -1);
});
Adil
  • 143,427
  • 25
  • 201
  • 198
2
$($("div[class*='TID_']").get().reverse()).each(function() {
    console.log(this);
});

Working Example http://jsfiddle.net/yBZT6/

Kevin Bowersox
  • 90,944
  • 18
  • 150
  • 184
0

If your items are ordered in a descendant way all you need to do is a reverse each. You can do it - as proposed in this response - like this:

$($("div[class*='TID_']").get().reverse()).each(function() { /* ... */ });
Community
  • 1
  • 1
TMichel
  • 4,026
  • 8
  • 43
  • 63