When a user clicks on a <li>
-element or on a child element of it, I want to add a class to this <li>
-element.
This works fine, but for performance enhancement I decided to bind this event to the <ul>
-element, so unbinding and binding this event is much faster in a list consisting of 1000 <li>
-elements. The only change I thought I had to make was to replace this
with event.target
BUT event.target
can also refer to a child element of a list item or even to a grandchild.
Is there an easy way to check this target element is part of a list item or do I need to walk the path from event.target
till I reach a <li>
element?
This is what I had before I decided to bind an event to the <ul>
tag, which works but is not fast enough:
$('#list li').mousedown(function(){
$(this).addClass('green');
});
And this is what I have now which doesn't work properly, mousedown on a child element doesn't give the <li>
another classname:
$('#list').mousedown(function(event){
if(event.target.nodeName == 'LI'){
$(event.target).addClass('green');
}
});
I wonder if my second way to achieve this is faster if there is not a simple solution to check if that target element is part of a list item...