My question refers specifically to http://api.jquery.com/event.target/#example-1
If you use a span in the <li>
or other tag to change the style such as <b>
as I have done here, that part of the element won't trigger the JQuery function to toggle it's children. How might one go about making this work?
HTML:
<ul>
<li><b>This doesn't work,</b> this does
<ul>
<li>sub item 1-a</li>
<li>sub item 1-b</li>
</ul>
</li>
<li>item 2
<ul>
<li>sub item 2-a</li>
<li>sub item 2-b</li>
</ul>
</li>
</ul>
JavaScript:
function handler(event) {
var $target = $(event.target);
if( $target.is("li") ) {
$target.children("ul").toggle();
}
}
$("ul").click(handler).find("ul").hide();
jQuery children() MethodThe children() method returns all direct children of the selected element. The DOM tree: This method only traverse a single level down the DOM tree. To traverse down multiple levels (to return grandchildren or other descendants), use the find() method.
target are obsolete, not that Event. target itself is obsolete. The DOM (Living Standard) specification is not marked as obsolete and you should use that definition.
The event. target property returns which DOM element triggered the event. It is often useful to compare event. target to this in order to determine if the event is being handled due to event bubbling.
Definition and Usage The target event property returns the element that triggered the event. The target property gets the element on which the event originally occurred, opposed to the currentTarget property, which always refers to the element whose event listener triggered the event.
To keep using your current form, I'd suggest using closest()
:
function handler(event) {
$(event.target).closest('li').children("ul").toggle();
}
$("ul").click(handler).find("ul").hide();
JS Fiddle demo.
Though for my own use I'd prefer:
$('li').on('click', function(e){
e.stopPropagation();
$(this).find('ul').toggle();
});
JS Fiddle demo.
References:
closest()
.on()
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With