There are two ways you can read value of HTML data-*
attributes:
Using dataset
Property
The DOMStringMap
interface provides access to data-*
attributes via dataset
property. When accessing data-*
attributes via the dataset
property, the value of attributes are read:
- Without the
data-
prefix, and; - 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'
This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.