How to Listen for Only Parent Events (Not Children) in JavaScript


I was writing out a component in React that required an overlay with some buttons on it, so I needed a way to differentiate parent element and child element events.

The overlay was the parent element and each button was a child element.

Let’s take this simple example. We have a parent and a child.

<div id="parent">
  <div id="child"></div>
</div>

Just to be thorough, suppose we style them with nice Christmas colors.

#parent {
  width: 50px; 
  height: 50px;
  background: green;
}
#child {
  width: 25px; 
  height: 25px;
  background: red;
}

We’ll attach an event listener to the parent element.

In order to distinguish clicking #parent from clicking #child, we can compare the event target and the event currentTarget.

document.getElementById("parent").addEventListener('click', e => {
  if(e.target !== e.currentTarget) console.log("child clicked") 
  else console.log("parent clicked")
});

e.target refers to the element that triggered the event (i.e. the element the user clicked on).

e.currentTarget refers to the element that the event listener is attached to.

In our case, e.currentTarget will always return the #parent element, but e.target will return whatever element the user directly interacted with.