I was making a menu today, and I stumbled on this curious case, with the following HTML:
<div id="list1">
<ul>
<li>1</li>
<li>2 - Here is a Submenu
<ul>
<li>3</li>
<li>4</li>
</ul>
</li>
</ul>
</div>
Then i used the following js:
$('#list1 li').click(function(){
$('.list-item').removeClass('list-item');
$(this).addClass('list-item');
});
When I do this the class would only be applied to the outer <li>, but I wanted it to be applied to both the parent and child LIs.
Now my question is, how can I handle this “returns” so I apply the classes to both the parent and child LIs?
How does js handle these type of selectors? Is the event really running twice and removing the last class that was set?
The issue is that
$('#list1 li')can select both levels oflitags inside#listand apply a click handler to both. In addition, you are allowing the click to propagate up so it may be seen by more than just the one you click on.If you only want the outer level, then you should use direct child specifications like this. and that will isolate what click handler is actually installed:
This will only get the top level
litags. And, the whole code would look like this:If you want to isolate the removeClass operation to just the other LI tags at the same level, not across the entire document, then you can use something like this:
Your comments have me a bit confused about this LI tags you want clickable. If you actually want the lower level to be clickable and then apply the list-item class to both the one that was clicked and the parent LI, then you can do that like this: