Languages
[Edit]
EN

JavaScript - get handle to clicked element

0 points
Created by:
Leen-Kerr
571

In this article, we would like to show you how to get a handle to the clicked element using JavaScript.

Quick solution:

document.body.addEventListener('click', function(event) {
    // refer to the clicked element as event.target
    // e.g:
    console.log(event.target.textContent);
});

 

1. Click handler on whole document body

In this example, we add an event listener to the document.body and pass event as an argument, so we can get handle to any element we click on within the body using event.target.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <script>
    
    document.body.addEventListener('click', function(event) {
        console.log(event.target.textContent);
    });

  </script>
  <div>Click the elements to display text in the console:</div>
  <div>div1 text...</div>
  <div>div2 text...</div>
  <div>div3 text...</div>
</body>
</html>

2. Click handler on separate elements

In this example, we create handleClick() function that takes one argument - the element we want to get and display its textContent. With this approach, we need to separately add an onclick property to each element we want to get and pass this as the handleClick() function argument.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <script>

    function handleClick(element) {
        console.log(element.textContent);
    }

  </script>
  <div>Click the elements below to display text in the console:</div>
  <div onclick="handleClick(this)">div1 text...</div>
  <div onclick="handleClick(this)">div2 text...</div>
  <div onclick="handleClick(this)">div3 text...</div>
</body>
</html>

References

  1. Event.target - Web APIs | MDN
  2. Node.textContent - Web APIs | MDN

Alternative titles

  1. JavaScript - get handle to clicked element anywhere in document body
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join