Dataset
The dataset read-only property of the HTMLElement interface provides read/write access to custom data attributes (data-*) on elements. It exposes a map of strings (DOMStringMap) with an entry for each data-* attribute.
Browser support
| Feature | Desktop | Mobile | ||||
|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Safari | Chrome Android | Safari iOS | |
| 7 | 12 | 6 | 5.1 | 18 | 5 | |
| The DOMStringMap interface is used for the HTMLElement.dataset attribute, to represent data for custom attributes added to elements. | 7 | 12 | 6 | 5.1 | 18 | 5 |
| The dataset read-only property of the MathMLElement interface provides read/write access to custom data attributes (data-) on elements. It exposes a map of strings (DOMStringMap) with an entry for each data- attribute. | 109 | 109 | 71 | 13.1 | 109 | 13.4 |
| The dataset read-only property of the SVGElement interface provides read/write access to custom data attributes (data-) on elements. It exposes a map of strings (DOMStringMap) with an entry for each data- attribute. | 55 | 17 | 51 | 5.1 | 55 | 5 |
Syntax
const el = document.querySelector("#user");
// el.id === 'user'
// el.dataset.id === '1234567890'
// el.dataset.user === 'carinaanand'
// el.dataset.dateOfBirth === ''
// set a data attribute
el.dataset.dateOfBirth = "1960-10-03";
// Result on JS: el.dataset.dateOfBirth === '1960-10-03'
// Result on HTML: <div id="user" data-id="1234567890" data-user="carinaanand" data-date-of-birth="1960-10-03">Carina Anand</div>
delete el.dataset.dateOfBirth;
// Result on JS: el.dataset.dateOfBirth === undefined
// Result on HTML: <div id="user" data-id="1234567890" data-user="carinaanand">Carina Anand</div>
if (el.dataset.someDataAttr === undefined) {
el.dataset.someDataAttr = "mydata";
// Result on JS: 'someDataAttr' in el.dataset === true
// Result on HTML: <div id="user" data-id="1234567890" data-user="carinaanand" data-some-data-attr="mydata">Carina Anand</div>
} Use cases
-
Using Dataset
The dataset read-only property
Cautions
- May not be supported in older browsers.
Implementation notes
- Some APIs require a secure context (HTTPS) or user activation. Check the requirements before use.