Home > Web Front-end > JS Tutorial > How do you add click event listeners to multiple elements with the same class in JavaScript?

How do you add click event listeners to multiple elements with the same class in JavaScript?

Barbara Streisand
Release: 2024-11-25 19:01:12
Original
535 people have browsed it

How do you add click event listeners to multiple elements with the same class in JavaScript?

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');
Copy after login

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

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template