Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you get the value of a data attribute?

To get a data attribute through the dataset object, get the property by the part of the attribute name after data- (note that dashes are converted to camelCase). Each property is a string and can be read and written.

How do you get all the attributes of an element in JS?

To get all of the attributes of a DOM element: Use the getAttributeNames() method to get an array of the element's attribute names. Use the reduce() method to iterate over the array. On each iteration, add a new key/value pair containing the name and value of the attribute.

How do you check if element has data attribute JavaScript?

Use the hasAttribute() method to check if a data attribute exists, e.g. if (el. hasAttribute('data-example')) {} . The hasAttribute method returns true if the provided attribute exists, otherwise false is returned.


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

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


You can access it as

element.dataset.points

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


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>

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

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>