Borislav Hadzhiev
Sun Dec 26 2021·2 min read
Photo by Tianshu Liu
Use the dataset
property to get all of the data-* attributes of a DOM
element, e.g. el.dataset
. The dataset
property provides read and write
access to the custom data attributes of the element. The property returns a
Map
of strings which can be converted to an object.
Here is the DOM element we will get the data attributes for.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box" data-bar="foo" data-id="example">Box 1</div> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const el = document.getElementById('box'); // 👇️ DOMStringMap {bar: 'foo', id: 'example'} console.log(el.dataset); // ✅ Optionally convert it to Object const obj = {...el.dataset}; console.log(obj); // 👉️ {bar: 'foo', id: 'example'}
We used the dataset property on the HTML element.
The property returns a read-only Map
of strings containing the custom data
attributes of the element.
The dataset
property itself is read-only. To update a specific property, we
must access the nested property.
console.log(el.dataset.id); // 👉️ "example" el.dataset.id = 'updated id'; console.log(el.dataset.id); // 👉️ "updated id"
To update the data-id
attribute, we accessed the id
property on the
dataset
object and assigned a new value to it.
If you want to convert the dataset
Map of strings to a native JavaScript
object, you can use the spread syntax (...).
// ✅ Optionally convert it to Object const obj = {...el.dataset}; console.log(obj); // 👉️ {bar: 'foo', id: 'example'}
You could also implement a minimal replacement for the dataset
property.
const el = document.getElementById('box'); const dataAttrs = el.getAttributeNames().reduce((obj, name) => { if (name.startsWith('data-')) { return {...obj, [name.slice(name.indexOf('-') + 1)]: el.getAttribute(name)}; } return obj; }, {}); console.log(dataAttrs); // 👉️ {bar: 'foo', id: 'example'}
We used the getAttributeNames
method to get the names of all of the attributes
of the DOM element.
The next step is to use the reduce()
method to iterate over the array of
attribute names.
On each iteration, we check if the attribute's name starts with data-
and if
it does we assign the key/value mapping to the object.
dataset
property and is only supposed to be used if for some reason you don't have access to the dataset
property.