0

The code below will call the function on every element inside the body. But I only want it for body element.

const bodyElement = document.querySelector("body");

bodyElement.addEventListener("click", function() {
  console.log("hello");
});

2 Answers2

1

The first argument to the event handler will be an Event object.

It has a target property that will tell you the element clicked on.

Compare it to bodyElement.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • For examples, see [here](https://stackoverflow.com/a/6203112/924299) and [here](https://stackoverflow.com/a/53815609/924299). – showdev Mar 21 '20 at 20:06
-1

Try to use this:

e.stopPropagation()

If I understand correctly, you want to use this only for one element, so...

matthias_h
  • 11,356
  • 9
  • 22
  • 40
  • 1
    "I only want [to call the function] for body element". So `stopPropagation` would need to be added for *every other* element, which doesn't seem efficient. – showdev Mar 21 '20 at 19:49