Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through all elements with class 'blah' and find the highest id value

Tags:

jquery

I have a bunch of elements like:

<div id="car-123" class="blah">..</div>

I want to loop through all of them and get the highest ID i.e. 123

how to do this?

Is below correct and the best way?

$(".blah").each(function() {

   var id = $(this).attr('id').split('-')[0];

   if( id > newid)
      newid = id;

});
like image 226
Blankman Avatar asked Jan 06 '11 20:01

Blankman


3 Answers

I would do:

var max = 0;
$(".blah").each(function(){
    num = parseInt(this.id.split("-")[1],10);
    if(num > max)
    {
       max = num;
    }
});

Most people would do this way.

like image 98
RobertPitt Avatar answered Nov 11 '22 15:11

RobertPitt


I'd go for this, using .map, .get and .sort:

$('.blah').map(function(){
    return parseInt(this.id.split('-')[1], 10);
}).get().sort(function(a, b) {
    return b - a;
})[0];
like image 21
lonesomeday Avatar answered Nov 11 '22 16:11

lonesomeday


You want to use parseInt so numerical operators apply

var id = parseInt($(this).attr('id').split('-')[1]);
like image 41
John Giotta Avatar answered Nov 11 '22 16:11

John Giotta