Home >Web Front-end >JS Tutorial >How to Handle Events for Multiple Elements with the Same Class in JavaScript?

How to Handle Events for Multiple Elements with the Same Class in JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-11-11 05:40:02316browse

How to Handle Events for Multiple Elements with the Same Class in JavaScript?

Event Handling for Elements with a Common Class

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.

Initial Approach with querySelector

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.

Solution with querySelectorAll

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');

Iterating and Adding Event Listeners

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();
        }
    });
}

Event Prevention Handling

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.

Demo and Extended Options

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn