Sometimes, we want to add an onclick event to a div element with JavaScript.
In this article, we’ll look at how to add an onclick event handler to a div element with JavaScript.
How to add an onclick event handler to a div element with JavaScript?
To add an onclick event handler to a div element with JavaScript, we set the div’s onclick property.
For instance, we write
<div id="thumb0" class="thumbs"></div>
to add a div.
Then we write
const div = document.getElementById("thumb0");
div.onclick = () => {
div.style.visibility = "visible";
};
to select the div with getElementById.
And then we set its onclick property to the click event handler function, which is called when we click on it.
Conclusion
To add an onclick event handler to a div element with JavaScript, we set the div’s onclick property.