Home > Article > Web Front-end > How to Access and Use Data Attribute Values in JavaScript?
Obtaining Data Attribute Values in JavaScript
In HTML, data attributes allow you to store data within elements without affecting their style or content. When working with JavaScript, you may want to access and utilize the values of these attributes.
Consider the following HTML markup:
<code class="html"><span data-typeId="123" data-type="topic" data-points="-1" data-important="true" id="the-span"></span></code>
Now, let's say you need to capture the data attributes that start with "data-" and extract the JSON representation of specific values. Initially, you may encounter null values or errors when attempting this:
<code class="javascript">document.getElementById("the-span").addEventListener("click", function() { var json = JSON.stringify({ id: parseInt(this.typeId), subject: this.datatype, points: parseInt(this.points), user: "H. Pauwelyn" }); });</code>
To resolve this, you must access the dataset property, which provides a map-like collection of all data attributes. The corrected JavaScript code would be:
<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>
This will successfully capture the desired values:
{ "id": 123, "subject": "topic", "points": -1, "user": "Luïs" }
By utilizing the dataset property, you can effortlessly access and manipulate data attributes in JavaScript, enabling more control and flexibility in your code.
The above is the detailed content of How to Access and Use Data Attribute Values in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!