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

How to Access and Use Data Attributes in JavaScript Code?

Mary-Kate Olsen
Release: 2024-10-25 16:43:02
Original
422 people have browsed it

How to Access and Use Data Attributes in JavaScript Code?

Retrieving Data Attributes in JavaScript Code

To access attributes beginning with "data-" in JavaScript code for the provided HTML element, you'll need to utilize the dataset property, as demonstrated in the code below:

<code class="js">document.getElementById("the-span").addEventListener("click", function() {
  var json = JSON.stringify({
    id: parseInt(this.dataset.typeid), // Accessing data-typedId attribute
    subject: this.dataset.type, // Accessing data-type attribute
    points: parseInt(this.dataset.points), // Accessing data-points attribute
    user: "H. Pauwelyn"
  });
});</code>
Copy after login

After executing this code, the json variable will contain an object with the following values:

{
  "id": 123,
  "subject": "topic",
  "points": -1,
  "user": "H. Pauwelyn"
}
Copy after login

This technique allows you to conveniently access and utilize data attributes in JavaScript code, simplifying the management and manipulation of custom attributes in your HTML markup.

The above is the detailed content of How to Access and Use Data Attributes in JavaScript Code?. 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!