Joshua Soileau
Joshua Soileau

Reputation: 3025

Iterate through elements, adding click event to each of them

jQuery newbie here.

If I have this html:

<ul id="floor-selector">
    <li id="floor-1">Ground Floor</li>
    <li id="floor-2">Second Floor</li>
    <li id="floor-3">Third Floor</li>
    <li id="floor-4">Premier Floor (Premier Floor)</li>
</ul>

I want to add a click event to each li item, such that I can get the id of the element I am on. Right now I just have an alert with the index I'm on (and it's not working either), but I really want the ID of the item I'm on, not the index of the array returned by my selector.

Here's what I tried, but it doesn't seem to work, I think I might have the wrong understanding of each() or click().

$('#floor-selector li').each( function(index, node) {
    node.click( function(){ alert('I am on the '+index+'th element'); } );
    // but I really want to get the ID of this element
  });

Upvotes: 2

Views: 3590

Answers (1)

Emil L
Emil L

Reputation: 21111

This should work:

$('#floor-selector li').on('click', function() {
    alert('I am the '+$(this).attr('id')+' element');
});

Behind the scenes jQuery does a bunch of magic and essentially binds the function you pass to the element. this therefore references the element that you are clicking and passing it to jQuery functio: $(this) gives you back that element wrapped in a jQuery object. Of course you could simply access the id on this directly.

Upvotes: 7

Related Questions