Coder Perfect

In JavaScript programming, how can I access the values of data attributes?

Problem

I’ve got the following html:

<span data-typeId="123" data-type="topic" data-points="-1" data-important="true" id="the-span"></span>

Is it possible to retrieve the data-prefixed attributes and utilize them in JavaScript code like the code below? For the time being, the result is nil.

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"
    });
});

Asked by H. Pauwelyn

Solution #1

The dataset property must be accessed:

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"
  });
});

Result:

// json would equal:
{ "id": 123, "subject": "topic", "points": -1, "user": "Luïs" }

Answered by Josh Crozier

Solution #2

Because Internet Explorer does not support the dataset property until version 11, you might wish to use getAttribute() instead:

document.getElementById("the-span").addEventListener("click", function(){
  console.log(this.getAttribute('data-type'));
});

Dataset documentation

getAttribute documentation

Answered by MarkPlewis

Solution #3

You can use it as a

element.dataset.points

etc. As an example, this.dataset.points

Answered by meskobalazs

Solution #4

You could also grab the attributes with the getAttribute() method which will return the value of a specific HTML attribute.

Answered by ii iml0sto1

Solution #5

If you’re looking for the data attribute in an HTML element,

document.dataset isn’t going to work.

you should use

document.querySelector("html").dataset.pbUserId

or

document.getElementsByTagName("html")[0].dataset.pbUserId

Answered by Basheer AL-MOMANI

Post is based on https://stackoverflow.com/questions/33760520/how-can-i-get-the-values-of-data-attributes-in-javascript-code