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,672
  • 8
  • 51
  • 96
Mihai Viteazu
  • 1,631
  • 3
  • 13
  • 15

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
  • 28,539
  • 11
  • 85
  • 132
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • @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
  • 146,340
  • 25
  • 209
  • 204
2
$($("div[class*='TID_']").get().reverse()).each(function() {
    console.log(this);
});

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

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
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,336
  • 9
  • 44
  • 67