Categories
JavaScript Answers

How to get the element clicked for the whole document with JavaScript?

Spread the love

To get the element clicked for the whole document with JavaScript, we add a click event handler for document.

For instance, we write

document.addEventListener(
  "click",
  (e) => {
    const target = e.target;
    const text = target.textContent;
  },
  false
);

to add a click handler for document with addEventListener.

In the click handler, we get the element that we clicked on with e.target.

And then we get the element’s text content with textContent.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *