Home >Web Front-end >JS Tutorial >How to Add Click Event Listeners to Multiple Elements with the Same Class?
Adding Click Event Listeners to Elements with the Same Class
In this scenario, you have a list view for deleting IDs and want to add a confirmation alert to all elements with the class "delete." However, you've encountered an issue where only the first element with the class seems to receive the listener.
Solution
To resolve this, you need to use querySelectorAll instead of querySelector. querySelectorAll returns a NodeList containing all elements with the specified class:
var deleteLink = document.querySelectorAll('.delete');
Now, you can iterate through the NodeList and add event listeners to each element:
for (var i = 0; i < deleteLink.length; i++) { deleteLink[i].addEventListener('click', function(event) { if (!confirm("sure u want to delete " + this.title)) { event.preventDefault(); } }); }
Additionally, only prevent the default action if the user does not confirm the deletion. This ensures that the deletion is only executed if the user explicitly chooses to proceed.
ES6 Enhancements
Using ES6, you can simplify the loop using Array.prototype.forEach:
Array.from(deleteLinks).forEach(link => { link.addEventListener('click', event => { if (!confirm(`sure u want to delete ${this.title}`)) { event.preventDefault(); } }); });
This version utilizes template strings (introduced in ES2015) for a cleaner syntax.
The above is the detailed content of How to Add Click Event Listeners to Multiple Elements with the Same Class?. For more information, please follow other related articles on the PHP Chinese website!