tags:

views:

236

answers:

2

I have ul li with the same idname

li id="name1"
li id="name2"
etc

i can add and remove li but the numbering not always good. How could i get the maximum name id?

Many thanks

+2  A: 

If they are guaranteed to appear sequentially in your document, you could do:

<li id="name1">Name1</li>
<li id="name2">Name2</li>

alert($("li[id^=name]:last").attr("id"));

or if you just need the number:

alert($("li[id^=name]").length);

where [id^=name] means that the id attribute starts with 'name'.

karim79
+1  A: 
function getLiIdWithMaxValue()
{
    var liIdMaxValue = 0;
    var lisWithName = $('LI[id^=name]'); //Use of @Karims79 terse selector
    for(var i = 0; i < lisWithName.length; i++) {
      var idNo = parseInt($(lisWithName[i]).attr('id'));
      if (idNo > liWithMaxName)
      {
        liIdMaxValue = idNo;
      }
    }
    return liIdMaxValue;    
}
mythz