Home > Web Front-end > JS Tutorial > How to Extract a Data Attribute from a Class on Click in JavaScript?

How to Extract a Data Attribute from a Class on Click in JavaScript?

Mary-Kate Olsen
Release: 2024-11-28 15:33:15
Original
190 people have browsed it

How to Extract a Data Attribute from a Class on Click in JavaScript?

Event Listeners and Class-Based Attribute Extraction in JavaScript

In JavaScript, adding event listeners to elements is crucial for interacting with the DOM. In this instance, you aim to retrieve an attribute from a class when clicked. The following code demonstrates the approach:

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 selects elements with the class name "classname," assigns them to an array-like object named elements, and then loops through the elements. For each element, an event listener is added to the 'click' event, which triggers the myFunction function when an element is clicked. Within this function, the getAttribute method retrieves the "data-myattribute" value of the clicked element and displays an alert with the attribute's value.

Remember, getElementsByClassName returns an array-like object, not an array. Therefore, the loop is necessary to traverse each element and add the event listener individually.

The above is the detailed content of How to Extract a Data Attribute from a Class on Click 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