Akinski
Akinski

Reputation: 13

Getting highest ID in Javascript

I have different spans in my HTML with each decimal ID's:

<span id="1">Lorem Ipsum</span>
<span id="23">Lorem Ipsum</span>
<span id="6">Lorem Ipsum</span>

I want to get the highest ID, using javascript. In this case it should return 23.

How can I do this?

Thanks.

Upvotes: 1

Views: 1916

Answers (4)

justkt
justkt

Reputation: 14766

Note these rules for your DOM ids for HTML 4 (HTML 5 has different rules). If you change to start with a letter you can remove the numeric part by using substring or a regular expression before parsing. The below code assumes a prefix (such as 's') of a letter before your numeric portion and is vanilla JS, no jQuery required.

// get all spans
var spans = document.getElementsByTagName("span");
var length = spans.length;
// variable for the highest one
var highest = 0;
// loop over to find the highest ID by looking at the property parsed as an int
for(var i = 0; i < length; i++) {
    var id= parseInt(spans[i].id.substring(1, spans[i].id.length), 10);
    if(id > highest) {
        highest = id;
    }
}
alert(highest);

see it in action

You can also do it in jQuery:

var highest = 0;
$("span").each(function() {
    var id = parseInt(this.id.substring(1, this.id.length), 10);
    if(id > highest) {
        highest = id;
    }
});
alert(highest);

See it in action

Upvotes: 6

Andrei Andrushkevich
Andrei Andrushkevich

Reputation: 9973

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

source

and my solution is:

var item = $('span').get(0);
var max_id = parseInt($(item).attr('id'));
$('span').each(function(){
   var curr_id = parseInt($(this).attr('id'));
   if (curr_id > max_id){
       max_id = curr_id;
       item = $(this);
   }
});

Upvotes: 0

lonesomeday
lonesomeday

Reputation: 237905

var els = document.getElementsByTagName('span'),
    highest = 0,
    i,
    cur;

for (i = 0; i < els.length; i++) {
    cur = parseInt(els[i].id, 10);
    if (els[i].id > highest) {
        highest = cur;
    }
}

highest will contain the highest value.

NB however that, in HTML4, it is illegal for an element ID to start with a non-alphabetic character:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods ("."). (source)

This is not an issue if you are using HTML5. And, what's more, it will probably work anyway.

Upvotes: 2

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114377

IDs must start with a letter. They cannot be numbers alone.

Upvotes: 2

Related Questions