JavaScript Reference ยท DOM: Document and Elements
HTMLElement.dataset
Reference for HTMLElement.dataset: read, write and delete custom data-* attributes as object properties, with the camelCase name mapping and value rules.
The dataset property exposes an element's custom data-* attributes as an object. An attribute such as data-user-id="42" becomes the property dataset.userId, with the value "42". You can read it, assign to it, and delete it, and the attributes in the HTML change accordingly.
Data attributes are a simple way to attach small pieces of information to markup, such as an id, a state or a configuration value, so your script and your CSS can both use it.
const id = button.dataset.userId; button.dataset.state = "open";
Try it
Syntax
element.dataset.propertyName element.dataset.propertyName = value delete element.dataset.propertyName "propertyName" in element.dataset
Name mapping:
| Attribute | Property |
|---|---|
data-id |
dataset.id |
data-user-id |
dataset.userId |
data-item-name |
dataset.itemName |
data-x-y-z |
dataset.xYZ |
When reading, each hyphen followed by a lowercase letter is removed and the letter is capitalized. When writing, each uppercase letter becomes a hyphen and the lowercase letter, so dataset.fooBar = "1" creates data-foo-bar.
Return value: a string, or undefined when the attribute does not exist. The dataset object itself is a DOMStringMap.
Exceptions: assigning to a name that contains a hyphen followed by a lowercase letter throws a SyntaxError (DOMException), because it could not be mapped back to an attribute.
Usage notes
- Values are strings. Assigned numbers, booleans and objects are converted with
String(), sodataset.on = falsestores"false", which is truthy. Convert on read withNumber()or a comparison like=== "true". - JSON in an attribute. For structured data you can store
JSON.stringify(value)and read it withJSON.parse(). Keep it small; large data belongs in a JavaScript variable. - Missing versus empty. A missing attribute reads as
undefined, butdata-flagwith no value reads as"". Check with"flag" in el.dataset. - Style hooks. Attribute selectors such as
[data-state="open"]let CSS react to values you set in JavaScript, without class names. - Event delegation. Putting
data-actionon buttons lets one listener on the parent decide what to do fromevent.target.closest("[data-action]").dataset.action. - Not private. Anything in
data-*is visible to users in the page source. Do not store secrets. - SVG and MathML.
datasetexists on allHTMLElement,SVGElementandMathMLElementobjects. - Prefix is case-sensitive in names. In HTML, attribute names are lowercased by the parser, so write
data-item-name, neverdata-itemName.
Browser support
Supported in all current browsers.
Related
Element.getAttribute()andsetAttribute()โ the underlying attribute APIElement.closest()โ find the element that carries the dataElement.classListโ another way to mark states- Lesson: Event delegation
- Lesson: Selecting elements