How can I get the values of data attributes in JavaScript code?

413,731

Solution 1

You need to access the dataset property:

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

Solution 2

Because the dataset property wasn't supported by Internet Explorer until version 11, you may want to use getAttribute() instead:

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

Dataset documentation

getAttribute documentation

Solution 3

You can access it as

element.dataset.points

etc. So in this case: this.dataset.points

Solution 4

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

var elem = document.getElementById('the-span');

var typeId = elem.getAttribute('data-typeId');
var type   = elem.getAttribute('data-type');
var points = elem.getAttribute('data-points');
var important = elem.getAttribute('data-important');

console.log(`typeId: ${typeId} | type: ${type} | points: ${points} | important: ${important}`
);
<span data-typeId="123" data-type="topic" data-points="-1" data-important="true" id="the-span"></span>

Solution 5

if you are targeting data attribute in Html element,

document.dataset will not work

you should use

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

or

document.getElementsByTagName("html")[0].dataset.pbUserId
Share:
413,731

Related videos on Youtube

H. Pauwelyn
Author by

H. Pauwelyn

I'm H. Pauwelyn, I'm working as software and web engineer at Savaco loving AI, robotics, new media, IoT, domotics, the cloud and Lego. The most common programming languages I use are C#, JavaScript, TypeScript and SQL.

Updated on April 26, 2022

Comments

  • H. Pauwelyn
    H. Pauwelyn about 2 years

    I have next html:

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

    Is it possible to get the attributes that beginning with data-, and use it in the JavaScript code like code below? For now I get null as result.

    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"
        });
    });
    
    • Peter Krauss
      Peter Krauss almost 5 years
      In nowadays (2019) it is also possible to use node's dataset property with SVG nodes (!), see answer below or use with D3.
  • Colin DeClue
    Colin DeClue over 8 years
    Asker didn't mention jQuery, this isn't even good jQuery for this purporse. Should be .data('type'); instead.
  • trincot
    trincot over 8 years
    And on top of that the suggestion to use this "instead of your code" is far too broad; the Asker would want to keep the event handling set-up, and JSON result, not an alert of the data-type attribute.
  • user3130012
    user3130012 almost 7 years
    this is jquery, not pure javascript.
  • Djonatan
    Djonatan over 5 years
    Bear in mind that according to MDN the datasets standard won't work for Internet Explorer < 11. developer.mozilla.org/en-US/docs/Learn/HTML/Howto/… "To support IE 10 and under you need to access data attributes with getAttribute() instead."
  • Sanira Nimantha
    Sanira Nimantha about 3 years
    any idea how this would work with typescript? since in typescript this gives an error, object maybe undefined
  • Damian
    Damian over 2 years
    With the explosion of frameworks such as Vue, React and Angular it goes against most of these frameworks practices to use jQuery. If the OP is using one of these then they should actively be avoiding jQuery. Additionally, they asked for it in JavaScript rather than jQuery which is why I've votes this down.
  • Mr.SwiftOak
    Mr.SwiftOak about 2 years
    it is better to add this as seoarate question so it will be properly answered
  • Adamakmar
    Adamakmar about 2 years