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 badges4 Answers
Reset to default 6You 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条)