Home  >  Article  >  Web Front-end  >  How to Access and Use Data Attributes in JavaScript Code?

How to Access and Use Data Attributes in JavaScript Code?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-25 16:43:02423browse

How to Access and Use Data Attributes in JavaScript Code?

Retrieving Data Attributes in JavaScript Code

To access attributes beginning with "data-" in JavaScript code for the provided HTML element, you'll need to utilize the dataset property, as demonstrated in the code below:

<code class="js">document.getElementById("the-span").addEventListener("click", function() {
  var json = JSON.stringify({
    id: parseInt(this.dataset.typeid), // Accessing data-typedId attribute
    subject: this.dataset.type, // Accessing data-type attribute
    points: parseInt(this.dataset.points), // Accessing data-points attribute
    user: "H. Pauwelyn"
  });
});</code>

After executing this code, the json variable will contain an object with the following values:

{
  "id": 123,
  "subject": "topic",
  "points": -1,
  "user": "H. Pauwelyn"
}

This technique allows you to conveniently access and utilize data attributes in JavaScript code, simplifying the management and manipulation of custom attributes in your HTML markup.

The above is the detailed content of How to Access and Use Data Attributes in JavaScript Code?. 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