HTML: data-* attributes
A data-* attribute stores a small custom value on an element so scripts or styles can use it.
What you will learn
- How to store a small supporting value with a
data-*attribute - How CSS attribute selectors and JavaScript
datasetuse the value - Why secrets and meaningful document content do not belong in custom attributes
Basic example
<button type="button" data-product-id="42" data-state="available">
Add to cart
</button>
Custom data attributes start with data- and use lowercase names with hyphens. They are useful for small values that support behavior without changing the visible text.
Read and write with dataset
const button = document.querySelector('button');
console.log(button.dataset.productId); // "42"
button.dataset.state = 'added';
The browser maps data-product-id to dataset.productId. Values are strings, so convert them when a number or boolean is required.
Use a value in CSS
[data-state="available"] {
border-color: seagreen;
}
[data-state="sold-out"] {
opacity: 0.6;
}
Attribute selectors can style a state, but do not use CSS alone to communicate important information or to implement behavior.
Common mistakes
- Putting important visible content only in a hidden data attribute.
- Expecting the browser to interpret a custom value automatically.
- Comparing a numeric value without remembering that
datasetreturns strings. - Using a data attribute as a replacement for a standard HTML attribute that already has the needed meaning.