How to Get Value of HTML data-* Attribute in JavaScript?

Get value of HTML data-* attributes in JavaScript

There are two ways you can read value of HTML data-* attributes:

  1. Using dataset Property;
  2. Using Element.getAttribute().

Using dataset Property

The DOMStringMap interface provides access to data-* attributes via dataset property. However, the value of attributes are read by specifying the name in camel case (instead of dashes). For example:

<div id="foo" data-total-count="123">foobar</div>
const foo = document.getElementById('foo');
const value = foo.dataset.totalCount;

console.log(value); // '123'

Using Element.getAttribute()

You can simply use the getAttribute() method to get the data attribute values, for example, in the following way:

<div id="foo" data-total-count="123">foobar</div>
const foo = document.getElementById('foo');
const value = foo.getAttribute('data-total-count');

console.log(value); // '123'

Hope you found this post useful. It was published . Please show your love and support by sharing this post.