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 i
If you click li ,you are current 2 step childnodes from parentNode div#div1
div#div1 > ul > li[current target] //back parentNode to 2 times
<script>
document.body.addEventListener('click', function(e){
if(e.target.parentNode.parentNode.id == "div1"){alert("hi")}
})
</script>
Here's with jquery for reference:
$("li").on('click', function(){
var y = this.parentElement.parentElement.id;
if (y === 'div1')
alert(y);
})
This event is attached to all <li>
elements within the Dom. You can follow the tree towards the root with parentElement
to access the <li>
containing <div>
element's id
property.
Alternatively:
$("div").on('click', function(){
var y = this.id;
if (y === 'div1')
alert(y);
})
However, this fires on every click within any <div>
element.
You should use e.target.parentNode.parentNode.id =='div1'
See the demo:
document.body.addEventListener('click', function(e) {
if (e.target.parentNode.parentNode.id == "div1") {
alert("hi")
}
})
<div id="div1">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<ul>
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 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:
document.body.addEventListener('click', function(e){
if(e.target.nodeName == "LI"){alert("hi")}
})