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

匿名 (未验证) 提交于 2019-12-03 02:56:01

问题:

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;  });

回答1:

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.



回答2:

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];


回答3:

You want to use parseInt so numerical operators apply

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


回答4:

I think you need the second value the splitted ID, and you might want to convert the string to an integer, like this:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!