312

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"
    });
});
H. Pauwelyn
  • 13,575
  • 26
  • 81
  • 144
  • 4
    In nowadays (2019) it is also possible to use node's dataset property with SVG nodes (!), see [answer below](https://stackoverflow.com/a/57540151/287948) or use [with D3](https://stackoverflow.com/a/57539693/287948). – Peter Krauss Aug 17 '19 at 21:49

11 Answers11

340

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" }
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
  • 5
    Bear in mind that according to MDN the datasets standard won't work for Internet Explorer < 11. https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes#Issues "To support IE 10 and under you need to access data attributes with getAttribute() instead." – Djonatan Nov 19 '18 at 18:51
  • 1
    any idea how this would work with typescript? since in typescript this gives an error, **object maybe undefined** – Sanira Nimantha Jun 22 '21 at 14:43
166

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

MarkPlewis
  • 2,310
  • 1
  • 15
  • 13
59

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

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

const typeId = elem.getAttribute('data-typeId');
const type   = elem.getAttribute('data-type');
const points = elem.getAttribute('data-points');
const 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>
ii iml0sto1
  • 1,654
  • 19
  • 37
55

You can access it as

element.dataset.points

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

meskobalazs
  • 15,741
  • 2
  • 40
  • 63
16

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
Basheer AL-MOMANI
  • 14,473
  • 9
  • 96
  • 92
6

Modern browsers accepts HTML and SVG DOMnode.dataset

Using pure Javascript's DOM-node dataset property.

It is an old Javascript standard for HTML elements (since Chorme 8 and Firefox 6) but new for SVG (since year 2017 with Chorme 55.x and Firefox 51)... It is not a problem for SVG because in nowadays (2019) the version's usage share is dominated by modern browsers.

The values of dataset's key-values are pure strings, but a good practice is to adopt JSON string format for non-string datatypes, to parse it by JSON.parse().

Using the dataset property in any context

Code snippet to get and set key-value datasets at HTML and SVG contexts.

console.log("-- GET values --")
var x = document.getElementById('html_example').dataset;
console.log("s:", x.s );
for (var i of JSON.parse(x.list)) console.log("list_i:",i)

var y = document.getElementById('g1').dataset;
console.log("s:", y.s );
for (var i of JSON.parse(y.list)) console.log("list_i:",i)

console.log("-- SET values --");
y.s="BYE!"; y.list="null";
console.log( document.getElementById('svg_example').innerHTML )
<p id="html_example" data-list="[1,2,3]" data-s="Hello123">Hello!</p>
<svg id="svg_example">
  <g id="g1" data-list="[4,5,6]" data-s="Hello456 SVG"></g>
</svg>
Peter Krauss
  • 13,174
  • 24
  • 167
  • 304
3

Circa 2019, using jquery, this can be accessed using $('#DOMId').data('typeId') where $('#DOMId') is the jquery selector for your span element.

den232
  • 682
  • 6
  • 14
-2

Example:

<input data-default-value="Default Value">Name</input>
inputEl.getAttribute("data-default-value")

→ returns: Default Value

H. Pauwelyn
  • 13,575
  • 26
  • 81
  • 144
SomeOne
  • 51
  • 4
-4
document.getElementById('selectTbl').addEventListener('change', function () {
    $("#selectTbl").val();
    var style = $(this).val() == 1 ? 'block' : 'none';
    document.getElementById('TblAdmin').style.display = style;

    var style = $(this).val() == 2 ? 'block' : 'none';
    document.getElementById('TblMech').style.display = style;

    var style = $(this).val() == 3 ? 'block' : 'none';
    document.getElementById('TblUser').style.display = style;

    var style = $(this).val() == 4 ? 'block' : 'none';
    document.getElementById('TblBiz').style.display = style;
});

Sorry to interrupt I think you already got the answer. Can someone help for me? Here I want to display the div which is TblAdmin, TblMech, TblUser, TblBiz. I'm currently using NiceSelect but inside the select dropdown it has data value attribute. It actually not select but list-item inside unordered-list.

Like picture shown here, https://drive.google.com/file/d/1VyHDMb1Gl4PYBe19XZt1Z8Z-2OLAS1mx/view?usp=sharing

Adamakmar
  • 45
  • 5
  • it is better to add this as seoarate question so it will be properly answered – Mr.SwiftOak Apr 25 '22 at 17:41
  • already but no one answered... https://stackoverflow.com/questions/71987887/get-value-from-niceselect/71987971?noredirect=1#comment127214672_71987971 – Adamakmar Apr 25 '22 at 17:53
-10

Try this instead of your code:

var type=$("#the-span").attr("data-type");
alert(type);
H. Pauwelyn
  • 13,575
  • 26
  • 81
  • 144
  • 19
    Asker didn't mention jQuery, this isn't even good jQuery for this purporse. Should be `.data('type');` instead. – Colin DeClue Nov 17 '15 at 17:01
  • 3
    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. – trincot Nov 17 '15 at 18:26
  • 1
    this is jquery, not pure javascript. – user3130012 Aug 16 '17 at 02:53
-10

You can actually use JQuery to accomplish that in a very easy way

$(document).on('click', '.the-span', function(){

let type = $(this).data("type");

});
iamnonso
  • 105
  • 1
  • 4
  • 2
    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. – Damian Oct 18 '21 at 17:09