The HTMLElement.dataset
property allows access, both in reading and writing mode, to all the custom data attributes (data-*) set on the element, either in HTML or in the DOM. It is a map of DOMString, one entry for each custom data attribute. Note that the dataset
property itself can be read, but not directly written. Instead, all writes must be to its "properties", which in turn represent the data attributes. Note also that an HTML data-
attribute and its corresponding DOM dataset.
property do not share the same name, but they are always similar:
data-
. It must contain only letters, numbers and the following characters: dash (-
), dot (.
), colon (:
), underscore (_
) -- but NOT any ASCII capital letters (A
to Z
).dash-style to camelCase: A custom data attribute name is transformed to a key for the DOMStringMap
entry with the following rules
data-
is removed (including the dash);U+002D
) followed by an ASCII lowercase letter a
to z
, the dash is removed and the letter is transformed into its uppercase counterpart;
camelCase to dash-style: The opposite transformation, that maps a key to an attribute name, uses the following rules:
a
to z
(before the transformation);data-
is added;A
to Z
is transformed into a dash followed by its lowercase counterpart;The restriction in the rules above ensures that the two transformations are the inverse one of the other.
For example, the attribute named data-abc-def
corresponds to the key abcDef
.
<div id="user" data-id="1234567890" data-user="johndoe" data-date-of-birth>John Doe</div> let el = document.querySelector('#user'); // el.id == 'user' // el.dataset.id === '1234567890' // el.dataset.user === 'johndoe' // el.dataset.dateOfBirth === '' el.dataset.dateOfBirth = '1960-10-03'; // set the DOB. // 'someDataAttr' in el.dataset === false el.dataset.someDataAttr = 'mydata'; // 'someDataAttr' in el.dataset === true
Specification | Status | Comment |
---|---|---|
WHATWG HTML Living Standard The definition of 'HTMLElement.dataset' in that specification. | Living Standard | No change from latest snapshot, HTML5.1 |
HTML5.1 The definition of 'HTMLElement.dataset' in that specification. | Recommendation | Snapshot of WHATWG HTML Living Standard, no change from HTML5 |
HTML5 The definition of 'HTMLElement.dataset' in that specification. | Recommendation | Snapshot of WHATWG HTML Living Standard, initial definition. |
Feature | Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|---|
Basic support | 8 | (Yes) | 6.0 (6.0) | 11 | 11.10 | 6 |
Feature | Android | Edge | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | 6.0 (6) | (Yes) | (Yes) | (Yes) |
© 2005–2017 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset