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

How to Access and Use Data Attributes in JavaScript?

Susan Sarandon
Release: 2024-10-25 11:19:02
Original
518 people have browsed it

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

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

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

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!

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!