Home >Web Front-end >JS Tutorial >How can I add event listeners to multiple elements in a single line of code?

How can I add event listeners to multiple elements in a single line of code?

Susan Sarandon
Susan SarandonOriginal
2024-10-26 08:29:03913browse

How can I add event listeners to multiple elements in a single line of code?

Adding Event Listeners to Multiple Elements in a Single Line

When working with multiple elements, it can be tedious to add event listeners to each one individually. Thankfully, there is a way to streamline this process and add event listeners to multiple elements in a single line of code.

Using a Loop

One effective method is to use a loop to iterate through an array of elements and add the event listener to each. For instance:

let elementsArray = document.querySelectorAll("whatever");

elementsArray.forEach(function(elem) {
    elem.addEventListener("input", function() {
        // This function does stuff
    });
});

This code selects all elements matching the specified selector and adds an event listener to each one for the "input" event.

Grammatical Concerns

You may have noticed the grammatical issue in your second example:

element1 && element2.addEventListener("input", function() {
    // this function does stuff
});

This syntax is grammatically incorrect. The correct way to write this would be:

(element1 && element2) && element2.addEventListener("input", function() {
    // this function does stuff
});

However, this method is still not efficient as it adds an event listener to each element separately. The loop approach outlined above is a more optimized solution.

The above is the detailed content of How can I add event listeners to multiple elements in a single line of code?. 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