Sometimes, we want to add click event listener to elements with the same class with JavaScript.
In this article, we’ll look at how to add click event listener to elements with the same class with JavaScript.
How to add click event listener to elements with the same class with JavaScript?
To add click event listener to elements with the same class with JavaScript, we can loop through each element and call addEventListener
on them.
For instance, we write
const deleteLinks = document.querySelectorAll(".delete");
Array.from(deleteLinks).forEach((link) => {
link.addEventListener("click", (event) => {
if (!confirm(`sure u want to delete ${event.target.title}`)) {
event.preventDefault();
}
});
});
to select all the elements with class delete
with `querySelectorAll“.
Then we convert deleteLinks
to an array with Array.from
.
And then we call forEach
with a function that calls link.addEventListener
to add a click listener to each element.
Conclusion
To add click event listener to elements with the same class with JavaScript, we can loop through each element and call addEventListener
on them.