Reputation: 365
I have following javascript code
$(document).on('click', $('#contact-list li'), function (e) {
The list is dynamically created and I need the clicked list item (li) in my function for his/her attributes so first I tried
$(e.target)
but that was the exact element clicked on inside the li. The parent of the parent of the parent
$(e.target).parent()...;
will eventually get me to the li but I can't seem to find a better way. Sorry in advance if there is an obvious answer.
Upvotes: 0
Views: 31
Reputation: 2082
If the click is occurring on an LI element, which is what you are trying to do with your jQuery statement, then the $(this) reference will allow you to access that object. The .closest() suggested by everyone is unnecessary.
$(document).on('click', '#contact-list li', function (e) {
console.log($(this));
}
Fiddle me this: http://jsfiddle.net/sytac5zg/
Upvotes: 0
Reputation: 8814
$(e.target).closest('li')
will return the item if it's a li
, or the closest parent that matches the query.
Upvotes: 0
Reputation: 359776
Use .closest('li')
to get the <li>
in question.
Don't pass a jQuery object to .on()
, just the selector:
$(document).on('click', '#contact-list li', callback);
and if the element with ID contact-list
exists when you're binding events, this will work:
$('#contact-list').on('click', 'li', callback);
http://api.jquery.com/on/#direct-and-delegated-events
Upvotes: 1