Home >Web Front-end >JS Tutorial >How to Handle Events for Multiple Elements with the Same Class in JavaScript?
In web applications, adding event listeners to multiple elements with the same class can be a common task. This allows for standardized behavior across similar elements, such as confirmation prompts for deletion.
Consider the following JavaScript code aimed at adding a click event listener to all elements with the class "delete":
var deleteLink = document.querySelector('.delete'); deleteLink.addEventListener('click', function(event) { event.preventDefault(); var choice = confirm("sure u want to delete?"); if (choice) { return true; } });
While this code initializes an event listener for one element with the "delete" class, it fails to register listeners for all such elements. This limitation arises from the use of querySelector, which returns only the first matching element.
To extend the event listening to multiple elements, querySelectorAll should be employed. This method returns a NodeList object containing all elements with the specified class. The following code snippet illustrates this:
var deleteLinks = document.querySelectorAll('.delete');
With the NodeList in hand, you can now iterate through its elements and add event listeners individually:
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(); } }); }
One adjustment is to prevent default behavior only when the confirmation is false. Previously, returning true was used, but event.preventDefault() is the proper approach in the context of event listeners.
A working demonstration of this solution can be found at: http://jsfiddle.net/Rc7jL/3/.
Additionally, note that an ES6 version exists, which utilizes Array.prototype.forEach iteration and template strings for improved code readability.
The above is the detailed content of How to Handle Events for Multiple Elements with the Same Class in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!