PLease anyone give me a solution for this. The problem is I am generating thd ids dynamically in an html page with jquery. I want to find the greatest Id if the ids are for eg: id0,id1,id2.......... PLease anyone give me a solution. Thankyou for reading.
If you're generating these in the order they occur in the page, which is likely the case, you can use that prefix (with the attribute-starts-with selector, ^=) and the :last selector, like this:
var lastIdInPage = $("[id^='idPrefixHere']:last").attr("id");
This gets the id attribute from the last occurring element in the page where the ID starts with that prefix...since you're normally generating sequentially as you generate the page, this usually is all you need to do. Hopefully this fits you case :)
Try:
alert($('element[id^="id"]:last').attr('id'));
Note: Since you have not specified, I assume that order of elements is ascending in the DOM.
If you're not adding the elements to the page so that they're in DOM order naturally, then you can find it like this:
function withMaxId() {
var max = -1, maxe = null;
$('[id^=id').each(function() {
var idv = parseInt(this.id.replace(/^id/, ''), 10);
if (idv > max) {
max = idv;
maxe = this;
}
});
return maxe; // change to just "max" if you only want the id value
}
Of course if you know more about the elements you could replace $('*') with something more selective.
working example of following code can be found at http://www.jsfiddle.net/LdgN9/2/
// create an array
var ar = new Array();
// for each element with id that starts with 'id'
$('[id^="id"]').each(
function(){
// add it to the array (only its numeric part)
ar.push(
// extract the numeric part to be added in the array
parseInt( $(this).attr('id').replace('id','') )
);
});
// find the max value in the array
alert('id' + Math.max.apply( Math, ar ));