Get all data-* attributes of a DOM Element using JavaScript

avatar

Borislav Hadzhiev

Sun Dec 26 20212 min read

banner

Photo by Tianshu Liu

Get all data-* attributes of a DOM Element #

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.

index.html
<!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.

index.js
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'}
For an alternative solution, scroll down to the next 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.

index.js
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 (...).

index.js
// โœ… Optionally convert it to Object const obj = {...el.dataset}; console.log(obj); // ๐Ÿ‘‰๏ธ {bar: 'foo', id: 'example'}
However, if you now update a specific property on the object, the changes will not get reflected in the DOM.

You could also implement a minimal replacement for the dataset property.

index.js
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.

This approach has many differences to the dataset property and is only supposed to be used if for some reason you don't have access to the dataset property.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee