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

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

Susan Sarandon
Release: 2024-11-09 18:30:03
Original
236 people have browsed it

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

Adding Click Event Listeners to Elements with the Same Class

To add a click event listener to all elements with a specific class, you can use querySelectorAll() instead of querySelector() to retrieve all matching elements.

JavaScript Code:

var deleteLinks = document.querySelectorAll('.delete');

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 this code:

  • var deleteLinks = document.querySelectorAll('.delete'); retrieves all elements with the class "delete".
  • The following for loop iterates through the list of elements.
  • For each element, an event listener is added to listen for the click event.
  • If the confirm("sure u want to delete " this.title) function returns false, the event.preventDefault() call prevents the default behavior of the click event (such as submitting a form).

Additional Notes:

  • It's worth noting that only querySelector() returns a single element, while querySelectorAll() returns a NodeList.
  • Using event.preventDefault() is appropriate for preventing form submissions or other default actions when using addEventListener().

The above is the detailed content of How do you add a click event listener 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