Sometimes, we want to add a click event listener on div tag using JavaScript.
In this article, we’ll look at how to add a click event listener on div tag using JavaScript.
How to add a click event listener on div tag using JavaScript?
To add a click event listener on div tag using JavaScript, we can call the addEventListener
method on the selected div.
For instance, we write:
<div class='drill_cursor'>
hello world
</div>
to add a div with a class.
Then we write:
const div = document.querySelector('.drill_cursor');
div.addEventListener('click', (event) => {
console.log('Hi!');
});
We select the div with document.querySelector
.
Then we call addEventListener
with 'click'
to add a click event listener.
And then we set the click event listener to a function that logs 'Hi!'
in the console.
Therefore, when we click on the div, we should see 'Hi!'
logged.
Conclusion
To add a click event listener on div tag using JavaScript, we can call the addEventListener
method on the selected div.