JavaScript
Article
By Sam Deering

jQuery Getting Highest id of Elements on Page

By Sam Deering
Help us help you! You'll get a... FREE 6-Month Subscription to SitePoint Premium Plus you'll go in the draw to WIN a new Macbook SitePoint 2017 Survey Yes, let's Do this It only takes 5 min

A jQuery code snippet to get the highest id of a specified group of elements on the page. Useful if you are giving an id to container elements and you need to load in the next element which needs to be higher than any of the current element ids. For example, loading products and storing the id of the products in a container div, then as the user scrolls down the page it can load in more products but grab the highest id to pass to the server side script to return the product data.

jquery-highest-id-of-elements

--ADVERTISEMENT--

Example DOM Structure

...
...
...
...

The Code

//filtered by class, but you could loop all elements
var highest = 0, this_id;
$(".item").each( function(i,v)
{
   this_id = parseInt($(this).attr('id'));
   console.log(this_id+">"+highest+"="+(this_id > highest));
   if (this_id > highest)
   {
      highest = this_id;
      console.log('new highest = ' + highest )
   }
});
console.log(highest);
Login or Create Account to Comment
Login Create Account
Recommended
Sponsors
Get the most important and interesting stories in tech. Straight to your inbox, daily.Is it good?