I'm trying to create one event listener to handle all my "clicks" by putting it on the body and doing some event delegation. A simple example of what i'm trying to do is this:
<html>
<body>
<div id = "div1">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<ul>
</div>
<script>
document.body.addEventListener('click', function(e){
if(e.target.id == "div1"){alert("hi")}
})
</script>
</body>
</html>
What I expect from the code above is that when I click on the "li" elements, the alert would fire since it is nested within the parent div. I thought that the event would propagate to the parent and fire. However, it doesn't seem to be working at all if I click on the li elements. Can someone help explain what's happening? Thank you!
If i was to do it the normal way by adding the eventListener directly to the div id, it would then work.
Here's with jquery for reference:
This event is attached to all
<li>
elements within the Dom. You can follow the tree towards the root withparentElement
to access the<li>
containing<div>
element'sid
property.Alternatively:
However, this fires on every click within any
<div>
element.You should use
e.target.parentNode.parentNode.id =='div1'
See the demo:There are two elements associated with an event:
These can be the same element, parent and child, or ancestor and descendant (which is the case here).
So a click on an LI makes it the target, and since the body's click handler calls the listener, it's the currentTarget, the DIV is neither. If you put the listener on the DIV, it will then become the currentTarget.
Originally, nodes other than elements could be event targets, but in recent implementations only elements are targets.
Some links:
Note that that target and eventTarget are specified as (host) objects, they aren't necessarily elements though that is how they are mostly implemented in current browsers.
If you click li ,you are current 2 step childnodes from parentNode
div#div1
If you want all the LI's in your body to be clicked, you can check against the nodeName.
Here is the fiddle: https://jsfiddle.net/swaprks/f3crax1q/
Javascript: