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

How do you access data attributes in JavaScript elements?

Barbara Streisand
Barbara StreisandOriginal
2024-10-27 08:38:31116browse

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>

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>

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>

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!

Statement:
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