EN
JavaScript - get handle to clicked element
0
points
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>