mokiSRB
mokiSRB

Reputation: 1162

Get id from each li

How to get the id of dynamic li elements?

<ul id="3" class="test">
    <li id="2">aca2</li>
    <li id="1">aca</li>
  </ul>
$('.test').each(function(){
    $(this).on('click', function(e){
        alert(this.id); //returns 3
    });
});

Upvotes: 1

Views: 114

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

You don't need the each() as you can bind the event directly to all child li elements of .test. Try this:

$('.test li').on('click', function(e) {
    alert(this.id);
});

Or if the li elements are dynamically appended you can use a delegated event handler:

$('.test').on('click', 'li', function(e) {
    alert(this.id);
});

what if I want to get input field value inside li

$('.test').on('click', 'li', function(e) {
    alert($(this).find('input').val());
});

Upvotes: 5

Carlos Gant
Carlos Gant

Reputation: 732

You could listen at click event using a selector. By this way you can also change dinamically the contents of the ul (ie: add/remove items) without affecting his behavior.

$('.test').on('click', 'li', function(event){
    alert($(event.target).attr('id'));
});

https://jsfiddle.net/adael/kf03rfg6/1/

Upvotes: 1

Related Questions