tags:

views:

57

answers:

4

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.

A: 

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

Nick Craver
A: 

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.

Sarfraz
That's assuming that the elements are placed in the DOM according to their numerical order. What if `id5` is before `id1`?
J-P
@J-P: That's right but i assume that order is in numerical in the DOM of course.
Sarfraz
+1  A: 

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.

Pointy
Off the top of my head, you could replace it with `[id^='id']` :)
Nick Craver
Well sure; in fact I probably should change it to make sure that there's an "id" value in the elements :-)
Pointy
@Pointy - `[id]` in the selector will speed it up in the smarter browser engines as well :) `[id^='id']` is doing the same thing as you are currently with the regex though, just using `.indexOf() == 0` though, http://github.com/jeresig/sizzle/blob/master/sizzle.js#L685
Nick Craver
Awesome information @Nick (as usual)!!
Pointy
+1  A: 

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