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

How to Access and Use Data Attributes in JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-10-25 11:19:02519browse

How to Access and Use Data Attributes in JavaScript?

Accessing Values of Data Attributes in JavaScript

In HTML, data attributes provide a way to store additional information about an element without affecting its visual presentation. To access these attributes in JavaScript code, you need to use the dataset property.

Consider the following HTML element with various data attributes:

<code class="html"><span data-typeId="123" data-type="topic" data-points="-1" data-important="true" id="the-span"></span></code>

To retrieve the values of these data attributes and use them in JavaScript code, you would write:

<code class="javascript">document.getElementById("the-span").addEventListener("click", function() {
  var json = JSON.stringify({
    id: parseInt(this.dataset.typeid),
    subject: this.dataset.type,
    points: parseInt(this.dataset.points),
    user: "Luïs"
  });
});</code>

The dataset property returns an object that contains all of the data attributes of an element, where the property names are the original attribute names with the "data-" prefix removed. In the code above, we use this object to populate a JSON object that can then be used for further processing or sent to a server.

The result of this code would be a JSON string representing the object:

<code class="json">{
  "id": 123,
  "subject": "topic",
  "points": -1,
  "user": "Luïs"
}</code>

This demonstrates how you can use the dataset property to access the values of data attributes in JavaScript code, allowing you to easily extract and manipulate this information for various purposes.

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