The JavaScript dataset property
The dataset property exposes an element's data-* attributes as an object. el.dataset.userId reads data-user-id, and setting it writes the attribute. Note the kebab-case attribute name becomes camelCase in dataset, and every value is a string.
Overview
HTML lets you attach custom data to any element with data-* attributes (data-id, data-user-name, data-state), and dataset is the clean JavaScript way to read and write them. Instead of getAttribute("data-id"), you write el.dataset.id; instead of setAttribute, you assign el.dataset.id = "42".
Two conversions to remember. The attribute name loses the data- prefix and switches from kebab-case to camelCase: data-user-id becomes dataset.userId. And every value is a string: numbers and booleans come back as strings, so Number(el.dataset.count) or a comparison like el.dataset.active === "true" is how you read them as their real types.
It's the idiomatic way to pass small pieces of data from your HTML (or server-rendered markup) to your JavaScript: an item's ID for a click handler, a config flag, a state value. For larger or structured data, store JSON in a single data-* attribute and JSON.parse() it. Keep data-* for genuine custom data, not for things HTML already has attributes for.
Syntax
// <div data-user-id="42" data-role="admin"></div>
el.dataset.userId // "42" (note camelCase, string value)
el.dataset.role // "admin"
el.dataset.userId = "99" // sets data-user-id="99"
Try it: data-* and dataset inspector
Edit either the HTML data-* attribute or the JS dataset key on a DOMStringMap, check string-type parsing traps, and watch CSS [data-state] update live.
Example
<button id="btn" data-product-id="42" data-price="19.99" style="font:15px system-ui;padding:8px 14px">Add to cart</button>
<p id="out"></p>
<script>
document.getElementById('btn').addEventListener('click', (e) => {
const id = e.target.dataset.productId;
const price = Number(e.target.dataset.price);
document.getElementById('out').textContent =
'product ' + id + ' costs $' + price.toFixed(2);
});
</script>
Common dataset recipes
Patterns for parsing typed values, delegating clicks on lists, and driving CSS states from data-* attributes.
Boolean("false") is true, and an empty boolean attribute (<div data-featured>) reads as "" (falsy); check presence with 'featured' in el.dataset.
const el = document.querySelector('#card');
const id = Number(el.dataset.productId); // 42
const inStock = el.dataset.inStock === 'true'; // true or false
const featured = 'featured' in el.dataset; // true for <div data-featured>
let meta = {};
try { meta = JSON.parse(el.dataset.meta || '{}'); } catch (e) {}
Bind one click listener on a parent container and read data-action and data-id via closest().
document.querySelector('#toolbar').addEventListener('click', (e) => {
const btn = e.target.closest('[data-action]');
if (!btn) return;
const { action, id } = btn.dataset;
console.log('Run action:', action, 'on item:', id);
});
Set el.dataset.state = "open" in JS and let CSS attribute selectors style the open and closed states.
.accordion[data-state="open"] .panel {
display: block;
}
.accordion[data-state="closed"] .panel {
display: none;
}
el.dataset vs getAttribute() vs CSS [data-*]
Use dataset for camelCase access on a live DOMStringMap, getAttribute() for literal attribute names or non-data attributes, and CSS attribute selectors for state styling.
| API | Name format | Missing | Delete | Best fit |
|---|---|---|---|---|
el.dataset.userId |
camelCase | undefined |
delete el.dataset.key |
Component state and event delegation |
el.getAttribute() |
kebab-case | null |
el.removeAttribute() |
Dynamic names, non-data attrs, hot loops |
CSS [data-state] |
kebab-case | No match | Remove attr in JS | Zero-class CSS state styling |
Best practices
- Use
datasetfor custom data; rememberdata-user-idmaps todataset.userId. - Convert values from their string form:
Number(el.dataset.count),el.dataset.on === "true". - Store structured data as JSON in one attribute and JSON.parse() it.
- Don't reinvent existing attributes (
id,href) asdata-*.
Browser compatibility
Supported via the DOMStringMap interface on HTMLElement, SVGElement, and MathMLElement across all modern browsers.
| Feature | Chrome | Edge | Firefox | Safari |
|---|---|---|---|---|
HTMLElement.dataset |
ChromeSupported since 7+ | EdgeSupported since 12+ | FirefoxSupported since 6+ | SafariSupported since 5.1+ |
SVGElement.dataset |
ChromeSupported since 55+ | EdgeSupported since 17+ | FirefoxSupported since 51+ | SafariSupported since 5.1+ |
MathMLElement.datasetAcross browsers since January 2023 |
ChromeSupported since 109+ | EdgeSupported since 109+ | FirefoxSupported since 71+ | SafariSupported since 13.1+ |
delete el.dataset.key |
ChromeSupported since 7+ | EdgeSupported since 12+ | FirefoxSupported since 6+ | SafariSupported since 5.1+ |
Frequently asked questions
How do I read a data attribute in JavaScript?
element.dataset.name. For data-user-id, that's element.dataset.userId (camelCase).Why is my dataset value a string?
data-* values are stored as strings. Convert with Number() or compare against "true"/"false" for other types.How does the name conversion work?
data- prefix and convert kebab-case to camelCase: data-order-total becomes dataset.orderTotal.What is the difference between dataset and getAttribute?
dataset is a convenient camelCase interface to data-* attributes; getAttribute() reads any attribute by its literal name.How do I delete a data-* attribute using dataset?
delete operator: delete el.dataset.userId. That removes data-user-id from the element. Assigning el.dataset.userId = undefined does not remove it; it writes the literal string "undefined".What happens with digits after hyphens (data-item-2) or uppercase HTML attributes?
a to z) becomes camelCase, so data-item-2 stays el.dataset["item-2"]. HTML parsers also lowercase attribute names, so data-userId maps to el.dataset.userid (not userId). In JavaScript, writing a DOMStringMap key with a hyphen before a lowercase letter (like el.dataset["user-id"] = "1") throws a SyntaxError.






















