Reputation: 20021
I have a simple ol li
based list which toggles when i click on parent item or child item. I want it to toggle only when parent item is clicked.
$("#expList > li").click(function () {
$(this).find("ol").slideToggle();
});
https://jsfiddle.net/k2jqqbbk/3/
I tried to target it with $("#expList ol li")
but this is not working. I tried few other options which didn't work either.
Upvotes: 1
Views: 178
Reputation: 2668
You need to target the a
tag. Because the ol
is the next child, the find
call has been replaced with a call to next
:
$("#expList > li > a").click(function () {
$(this).next().slideToggle();
});
If you want the functionality to extend to children of children, just omit #expList
from the selector:
$("li > a").click(function () {
$(this).next().slideToggle();
});
Upvotes: 1
Reputation: 20260
You could use the event.target
to check whether its closest li
contains an ol
, and only toggle if it does:
$('#expList > li').click(function(evt) {
if ($(evt.target).closest('li').has('ol').length) {
$(this).find("ol").slideToggle();
}
});
Upvotes: 2
Reputation: 1587
The click event bubbles up to ancestor elements. So the click is fired first against the second-level list items, then bubbles up to the first-level list items. This is why you're seeing the toggling happen.
All you need to do is stop the click event bubbling up the element chain from the second-level list items.
Add this to fix:
$("#expList ol li").click(function(e) {
e.stopPropagation();
});
Here's the example: https://jsfiddle.net/sxn5bg3x/
Upvotes: 0
Reputation: 98
Try to add the following code :
$("#expList > li").click(function () {
$(this).find("ol").slideToggle();
});
$("#expList > li ol li").click(function () {
return false;
});
Upvotes: 0