Sometimes, we want to get an HTML element in which a mouse click occurred with JavaScript.
In this article, we’ll look at how to get an HTML element in which a mouse click occurred with JavaScript.
How to get an HTML element in which a mouse click occurred with JavaScript?
To get an HTML element in which a mouse click occurred with JavaScript, we can use the e.target
property in the document’s click event listener.
For instance, we write:
<div>
foo
</div>
<section>
bar
</section>
to add some elements.
Then we write:
document.onclick = (e) => {
console.log(e.target.tagName)
}
to add a click event listener to document
which is the page.
In the click listener, we log the e.target.tagName
, which has the tag name of the element that we clicked on.
e.target
is the element we clicked on.
Therefore, when we click on the div, we see 'DIV'
logged.
And when we click on the section element, we see 'SECTION'
logged.
Conclusion
To get an HTML element in which a mouse click occurred with JavaScript, we can use the e.target
property in the document’s click event listener.