Jason Small
Jason Small

Reputation: 1054

Find the value of a div id based on partial match

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?

Upvotes: 2

Views: 1853

Answers (4)

Blender
Blender

Reputation: 298156

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

Upvotes: 1

xdazz
xdazz

Reputation: 160833

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

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

Upvotes: 0

Sarfraz
Sarfraz

Reputation: 382696

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.

Upvotes: 6

Alec Gorge
Alec Gorge

Reputation: 17390

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]

Upvotes: 2

Related Questions