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
Mary-Kate OlsenOriginal
2024-11-28 15:33:15208browse

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);
}

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!

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