Home >Web Front-end >JS Tutorial >How do you add a click event listener to multiple elements with the same class in JavaScript?
Adding Click Event Listeners to Elements with the Same Class
To add a click event listener to all elements with a specific class, you can use querySelectorAll() instead of querySelector() to retrieve all matching elements.
JavaScript Code:
var deleteLinks = document.querySelectorAll('.delete'); for (var i = 0; i < deleteLinks.length; i++) { deleteLinks[i].addEventListener('click', function(event) { if (!confirm("sure u want to delete " + this.title)) { event.preventDefault(); } }); }
In this code:
Additional Notes:
The above is the detailed content of How do you add a click event listener to multiple elements with the same class in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!