Home > Web Front-end > JS Tutorial > body text

How to Access and Use Data Attribute Values in JavaScript?

Barbara Streisand
Release: 2024-10-26 00:37:02
Original
436 people have browsed it

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

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

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

This will successfully capture the desired values:

{ "id": 123, "subject": "topic", "points": -1, "user": "Luïs" }
Copy after login

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!