tags:

views:

167

answers:

2
< ul id='myid' >  
< li id='1' >First< /li >  
< li id='2' >Second< /li >  
< li id='3' >Third< /li >  
< li id='4' >Fourth< /li >  
< li id='5' >Fifth< /li >  
  </ul>  

How can I alert the id of the li item clicked(anything that can replace the id may be value or something else will also work)
please help
thanks in advance
Dave

+3  A: 
$("#myid li").click(function() {
    alert(this.id); // get id of clicked li
    alert($(this).html()); // gets innerHTML of clicked li
    alert($(this).text()); // gets text contents of clicked li
});

If you are talking about replacing the ID with something:

$("#myid li").click(function() {
    this.id = 'newId';

    // longer method using .attr()
    $(this).attr('id', 'newId');
});

Demo here. And to be fair, you should have first tried reading the documentation:

karim79
Thanks Karim, It's working. Dave
dave
A: 

If you change your html code a bit - remove the ids

<ul id='myid'>  
<li>First</li>
<li>Second</li>
<li>Third</li>
<li>Fourth</li>
<li>Fifth</li>
</ul>

Then the jquery code you want is...

$("#myid li").click(function() {
    alert($(this).prevAll().length+1);
});​

You don't need to place any ids, just keep on adding li items.

Take a look at demo

Useful links

ShiVik
Thanks Shivik, but id is already defined. And I got the answer which I was looking for, in first answer. Thank again
dave