In HTML elements, data attributes provide a convenient way to store additional information. However, accessing these attributes in JavaScript can be tricky. Let's delve into a specific issue and explore its solution.
Consider the following HTML code:
<code class="html"><span data-typeId="123" data-type="topic" data-points="-1" data-important="true" id="the-span"></span></code>
In JavaScript, we aim to retrieve these data attributes and use them in a JSON object, as shown below:
<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>
However, attempting to access the data attributes using this.typeId, this.datatype, and this.points yields null.
To access data attributes in JavaScript, we must use the dataset property. Here's the modified code that accomplishes our goal:
<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 resulting JSON object would contain the desired data:
<code class="json">{ "id": 123, "subject": "topic", "points": -1, "user": "Luïs" }</code>
By leveraging the dataset property, we can effortlessly retrieve data attributes in JavaScript, enabling us to utilize their values in our code.
The above is the detailed content of How to Access Data Attributes in JavaScript: Why `this.typeId` Doesn\'t Work and How to Use `dataset` Instead?. For more information, please follow other related articles on the PHP Chinese website!