javascript - Find the value of a div id based on partial match - Stack Overflow

I have several divs on a page. They are formatted like:<div id='profile-1'><div>

I have several divs on a page. They are formatted like:

<div id='profile-1'></div>
<div id='profile-2'></div>
<div id='profile-3'></div>
<div id='profile-4'></div>

I need to find the value of the div with the highest id. In the previous example it would be "profile-4" (because 4 is the highest).

I've figured out how to search through the divs by using:

var elements = $('[id^=profile-]')

This returns an object. I need to take that object and figure out that "profile-4" is the highest and if possible extract the value "4".

Any ideas?

I have several divs on a page. They are formatted like:

<div id='profile-1'></div>
<div id='profile-2'></div>
<div id='profile-3'></div>
<div id='profile-4'></div>

I need to find the value of the div with the highest id. In the previous example it would be "profile-4" (because 4 is the highest).

I've figured out how to search through the divs by using:

var elements = $('[id^=profile-]')

This returns an object. I need to take that object and figure out that "profile-4" is the highest and if possible extract the value "4".

Any ideas?

Share Improve this question asked Jan 29, 2012 at 5:54 Jason SmallJason Small 1,0541 gold badge13 silver badges30 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 6

You can do:

var highest = 0;
$('[id^=profile-]').each(function(){
   var id = parseInt(this.id.split('-')[1], 10);
   highest = id > highest ? id : highest;
});

alert(highest); // 4

This will work even if you have different order eg:

<div id='profile-1'></div>
<div id='profile-20'></div>
<div id='profile-3'></div>
<div id='profile-4'></div>

In this case, 20 will be alerted.

Here is just another way to do it: if the the div's are always in ascending order (like in your HTML snippet you provided), you can do this:

$('div[id^=profile-]').get().reverse()[0]

Building on @Sarfraz's answer, you can use map to build beautifully obfuscated code:

var highest = Math.max.apply(null, $('[id^="profile-"]').map(function() {
  return [parseInt(this.id.split('-')[1], 10)];
}));

console.log(highest);
var highest = Math.max.apply(null, $.map($('[id^=profile-]'), function(el) {
    return el.id.split('-')[1];
});)

var highest_div = $('#profile-'+highest);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744946842a4602671.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信