jQuery Getting Highest id of Elements on Page

Sam Deering

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.


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 )