Home > Web Front-end > JS Tutorial > How to Properly Attach a Click Event Listener to Multiple Elements with the Same Class in JavaScript?

How to Properly Attach a Click Event Listener to Multiple Elements with the Same Class in JavaScript?

DDD
Release: 2024-11-30 14:02:10
Original
554 people have browsed it

How to Properly Attach a Click Event Listener to Multiple Elements with the Same Class in JavaScript?

JavaScript Event Listener for Clicks on Class

To attach a click event listener to a class, you can use the addEventListener() method. This method takes three arguments:

  • The event type (e.g., 'click')
  • A listener function
  • An optional capture flag (usually false)

In your example, you are using the addEventListener() method correctly. However, there are two issues:

1. Element Selection Mistake

You are selecting the class elements using document.getElementsByClassName("classname"), which returns an HTMLCollection or a NodeList (depending on the browser). These are not arrays, so you cannot use the array bracket notation to directly attach an event listener to each class element.

2. Event Listener Function Error

In your event listener function, you are calling it when you attach it to the class elements. This means the function is immediately executed when the listener is added. Instead, you should pass in the function as a reference without calling it:

classname.addEventListener('click', myFunction, false);
Copy after login

Corrected Code

Here is the corrected code:

var elements = document.getElementsByClassName("classname");

var myFunction = function() {
    var attribute = this.getAttribute("data-myattribute");
    alert(attribute);
};

for (var i = 0; i < elements.length; i++) {
    elements[i].addEventListener('click', myFunction, false);
}
Copy after login

This code will now correctly add an event listener to each class element and trigger the provided function when the element is clicked, displaying the element's data-myattribute attribute value in an alert.

The above is the detailed content of How to Properly Attach 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template