Skip to content
Tutorials Center
My learning

Topics

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.

JavaScript
const id = button.dataset.userId;
button.dataset.state = "open";

Try it

Reading, writing and deleting
Data attributes drive CSS and JavaScript

Syntax

JavaScript
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(), so dataset.on = false stores "false", which is truthy. Convert on read with Number() or a comparison like === "true".
  • JSON in an attribute. For structured data you can store JSON.stringify(value) and read it with JSON.parse(). Keep it small; large data belongs in a JavaScript variable.
  • Missing versus empty. A missing attribute reads as undefined, but data-flag with 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-action on buttons lets one listener on the parent decide what to do from event.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. dataset exists on all HTMLElement, SVGElement and MathMLElement objects.
  • Prefix is case-sensitive in names. In HTML, attribute names are lowercased by the parser, so write data-item-name, never data-itemName.

Browser support

Supported in all current browsers.