Home > Web Front-end > JS Tutorial > How to Access Data Attributes in JavaScript: Why `this.typeId` Doesn\'t Work and How to Use `dataset` Instead?

How to Access Data Attributes in JavaScript: Why `this.typeId` Doesn\'t Work and How to Use `dataset` Instead?

DDD
Release: 2024-10-26 06:42:30
Original
1089 people have browsed it

How to Access Data Attributes in JavaScript: Why `this.typeId` Doesn't Work and How to Use `dataset` Instead?

Obtaining Data Attributes in JavaScript

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.

The Challenge

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>
Copy after login

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>
Copy after login

However, attempting to access the data attributes using this.typeId, this.datatype, and this.points yields null.

The Solution

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>
Copy after login

The resulting JSON object would contain the desired data:

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

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template