The HTML data attribute
Custom data-* attributes attach private, custom data to any element, e.g. data-user-id="42". Read and write them in JavaScript through the dataset property (el.dataset.userId) and reach them in CSS with attribute selectors and attr(). They are global attributes.
Overview
A data-* attribute is any attribute whose name begins with data-. It lets you store extra information on an element without inventing non-standard attributes or abusing class names.
In JavaScript every data-* attribute appears on the element's dataset object, with the name converted from kebab-case to camelCase: data-user-id becomes el.dataset.userId. In CSS you can match them with attribute selectors ([data-state="open"]) and even print them with content: attr(data-label). Use data-* for scripting hooks and small bits of state — not for data that already has a semantic element or ARIA attribute.
Syntax
<article data-id="42" data-category="news" data-featured>
…
</article>
<!-- Read in JavaScript -->
el.dataset.id; // "42"
el.dataset.category; // "news"
<!-- Match in CSS -->
[data-featured] { font-weight: 700; }
Values
| Value |
|---|
| data-* — any attribute name starting with "data-" followed by lowercase letters, digits or hyphens. |
Example
<button id="save" data-action="save" data-id="42">Save</button>
<p id="out"></p>
<script>
var b = document.getElementById('save');
document.getElementById('out').textContent =
'action = ' + b.dataset.action + ', id = ' + b.dataset.id;
</script>
Best practices
- Name them in lowercase with hyphens (
data-order-id); they map to camelCase indataset. - Use them for scripting hooks and small UI state, not as a database — never store secrets, since they are visible in the page source.
- Do not reinvent semantics: if ARIA or a real element conveys the meaning, use that instead.
- Values are strings — serialise objects to JSON if you need structured data.
Accessibility
data-* attributes are invisible to assistive technology — they are never announced. Do not use them to convey state or labels to screen-reader users; use the appropriate ARIA attribute (such as aria-expanded or aria-label) for that, and keep data-* for your scripts.
Frequently asked questions
What are HTML data attributes?
data- that let you store extra information on any element, e.g. data-id="42".How do I read a data attribute in JavaScript?
dataset property. data-user-id becomes element.dataset.userId (kebab-case turns into camelCase).Can CSS use data attributes?
[data-state="open"] and display them with content: attr(data-label).When should I NOT use a data attribute?
data-* values are plainly visible in the DOM.