Home > Web Front-end > JS Tutorial > How do you access data attributes in JavaScript elements?

How do you access data attributes in JavaScript elements?

Barbara Streisand
Release: 2024-10-27 08:38:31
Original
217 people have browsed it

How do you access data attributes in JavaScript elements?

Getting Data Attributes in JavaScript

When dealing with HTML elements that have data attributes, such as data-type or data-points, accessing their values in JavaScript can be a challenge. Let's explore how to retrieve these data attributes in JavaScript code.

Accessing Data Attributes Using dataset

The dataset property allows you to access all data attributes of an element whose names start with "data-". To obtain the value of a specific data attribute, simply use the property name without the "data-" prefix. For instance, to get the value of the data-type attribute, you would use this.dataset.type.

Example Usage

Consider the following HTML element:

<code class="html"><span data-typeId="123" data-type="topic" data-points="-1" data-important="true" id="the-span"></span></code>
Copy after login

When an event occurs on this element, you can access its data attributes within the event handler function:

<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: "H. Pauwelyn"
  });
});</code>
Copy after login

Result

The json variable will now contain an object with the values of the data attributes:

<code class="json">{"id": 123, "subject": "topic", "points": -1, "user": "H. Pauwelyn"}</code>
Copy after login

The above is the detailed content of How do you access data attributes in JavaScript elements?. 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