Search code examples
jqueryhtmldhtml

jQuery get the id/value of <li> element after click function


How can I alert the id of the <li> item clicked?

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

(Anything that can replace the id may be value or something else will also work.)


Solution

  • $("#myid li").click(function() {
        alert(this.id); // id of clicked li by directly accessing DOMElement property
        alert($(this).attr('id')); // jQuery's .attr() method, same but more verbose
        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: