Adding Click Event Listeners to Multiple Elements with the Same Class
To add a click event listener to all elements with a particular class, you can use the querySelectorAll() method instead of querySelector(). The querySelector() method returns the first matching element, while querySelectorAll() returns a NodeList of all matching elements.
Solution:
var deleteLinks = document.querySelectorAll('.delete');
Now that you have a NodeList of all the delete links, you can loop through them and add an event listener to each one.
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 the event listener, you can use the this keyword to refer to the current element. This allows you to access the title attribute of the element and display a confirmation message to the user.
Note: It's important to use event.preventDefault() to prevent the default action of the link from taking place if the user confirms the deletion.
ES6 Version:
Using ES6, you can simplify the code using the forEach() method:
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 do you add click event listeners to multiple elements with the same class in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!