Data Attributes and Custom Data
How data-* attributes store custom values on elements, how dataset maps names and values, and how CSS can read them, plus what not to put in them.
Data Attributes and Custom Data
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- Any attribute starting with `data-` is yours. HTML will never give it meaning, so it is a safe place to hang small values on elements for scripts and CSS.
- In JavaScript, `element.dataset` maps `data-user-id` to `dataset.userId`. Values are always strings: `data-is-admin="false"` is the truthy string "false".
- Setting `dataset.x` writes the attribute, and `delete dataset.x` removes it. HTML lowercases attribute names, so `data-Upper` became `dataset.upper` in a test.
- CSS reads data attributes with attribute selectors like `[data-state="open"]`, which makes them a clean hook for state without extra classes.
- Data attributes are not exposed to assistive technology and are visible in the source. Don't use them for meaning a user needs or for secrets.
A drawer HTML leaves empty on purpose
Scripts often need a little extra information about an element: which product this card represents, which tab a button opens, whether a panel is expanded. You could encode it in a class (product-42), but that mixes styling with data, or keep a lookup table in JavaScript that has to match the markup.
HTML reserves a namespace for this. Any attribute whose name starts with data- is yours, and the standard promises never to assign it a meaning. Think of it as a labelled drawer on every element that the browser agrees not to touch.
<button data-product-id="42" data-in-stock="false">Add to cart</button>
dataset: attribute to property
In script, element.dataset is a live view of those attributes. The name rule: strip data-, then turn each dash-letter into a capital. I tested in Chromium, Firefox and a WebKit build, with identical results:
data-user-id="42"gavedataset.userId, a string “42”.data-is-admin="false"gave the string “false”, and!!dataset.isAdminwastrue.dataset.userId = 7set the attribute to “7”, and reading it back gave the string “7”.dataset.newThing = "n"createddata-new-thing, anddelete dataset.labelremoveddata-label.- A missing key returned
undefined. data-Upper="x"appeared asdataset.upper, because the HTML parser lowercases attribute names.
Everything is a string. For numbers use Number(...), and for structures store JSON and JSON.parse it, as I did with data-json='{"a":1}', but keep it small.
CSS can read them
Attribute selectors turn data attributes into state hooks:
.card[data-state="open"] { outline: 2px solid; }
In the test, flipping data-state to “open” with setAttribute changed the computed outline at once. The attr() function can also pull a value into generated content, as in ::after { content: attr(data-label) }. This pairs well with details and popover state, though those already have [open] and :popover-open. Note that attr() with types beyond strings is newer and less supported, so I only rely on the string form.
What not to put there
- Meaning users need. In Chromium’s accessibility tree a
data-*attribute gave no information at all. Put real information in text or semantics. - Secrets. They are in the source, readable by anyone, and editable in DevTools.
- Large data. Repeating it on every element bloats the HTML; for big sets, ship JSON and look it up by id.
- Things HTML already models. Use
disabled,hiddenandaria-expandedfor what they mean, notdata-disabled.
When you want a typed, validated, branded thing, you are heading towards custom elements. Frameworks use data attributes heavily as hooks too, as in the DOM and events lesson in frontend.
What the video covers
iEatWebsites’ “How to use the DATA attribute with JavaScript, HTML and CSS.” (January 2022, about 10 minutes). Its description says using the data attribute is easy and shows how a site can behave in interesting ways, assuming basic HTML, CSS and JS, and links MDN’s guide. I could not read a transcript. It is a modest-sized channel and a general tutorial, so the specifics above (string conversion, the lowercasing, the test results) are my own. OpenJavaScript’s shorter tutorial is the runner-up.
Where this fits
This follows the popover lesson as a bridge from built-in widgets to your own. Template and slot is next, and uses data attributes when stamping out markup.
Check yourself
What does `el.dataset.isAdmin` return for `data-is-admin="false"`, and what is the trap?
The string "false", which is truthy. In a test `!!dataset.isAdmin` was true. Compare to the string, or parse with `JSON.parse`.
How do you style a card differently when its `data-state` becomes "open"?
Write a selector like `.card[data-state="open"]`. In a test, setting the attribute with `setAttribute` or via `dataset.state` immediately applied the matching rule.
Is a `data-price` attribute a good way to give screen reader users the price?
No. It is not part of the accessibility tree. Put information users need in visible text or proper semantics, and use `data-*` only for script and style hooks.
How are the attribute `data-user-id` and the property `dataset.userId` related?
Dash-lowercase becomes camelCase. Setting `dataset.userId = 7` wrote `data-user-id="7"` in a test and read back as the string "7".
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.