Vitaly
Vitaly

Reputation: 4498

JQuery: get child under cursor of a clicked parent

Say we have a basic list like this:

<ul id="list">
  <li></li>
  <li></li>
  <li></li>
</ul>

$('#list').on('click', function() {
  // how to get the li element that was clicked within the ul element?
});

Upvotes: 1

Views: 478

Answers (2)

Andreas Wong
Andreas Wong

Reputation: 60536

Not sure why you won't want to assign click event to li directly instead, but I assume you want to do something with ul later in your code, so how about doing it the other way around?

$('#list li').on('click', function() {
   // if you need to get parent, do
   var parent = $(this).parent();
});

Upvotes: 0

Bogdan Emil Mariesan
Bogdan Emil Mariesan

Reputation: 5647

This is very simple:

$('#list').on('click','li', function() {
  // how to get the li element that was clicked within the ul element?
});

By adding a selector as an extra argument to the .on() method you get access to the element that triggers the event.

Upvotes: 3

Related Questions