Home > Article > Web Front-end > How to Add Event Listeners to Multiple Elements with the Same Class in JavaScript?
Adding Event Listeners to Multiple Elements with the Same Class
In web development, it's often necessary to add event listeners to multiple elements with the same class. This can be achieved using JavaScript's querySelectorAll() method.
Initial Problem:
The provided code snippet attempts to add an event listener to all elements with the "delete" class. However, it only adds the listener to the first element with that class, even though the intended behavior is to add it to all such elements.
Solution:
To resolve this issue, it's necessary to use querySelectorAll() instead of querySelector() to select all elements with the "delete" class. querySelector() only returns the first matching element, while querySelectorAll() returns a NodeList containing all matching elements.
The revised 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(); } }); }
With this code, an event listener is successfully added to each element with the "delete" class.
Other Considerations:
Array.from(deleteLinks).forEach(link => { link.addEventListener('click', function(event) { if (!confirm(`sure u want to delete ${this.title}`)) { event.preventDefault(); } }); });
The above is the detailed content of How to Add Event Listeners to Multiple Elements with the Same Class in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!