data-* – custom data (attribute)
<element data-name="value">
Custom data on an element: a product id, a price, a state, the settings of a component. A script reads and changes them via element.dataset, CSS selects them with an attribute selector ([data-state="sold-out"]). Unlike made-up attributes (price="4.50") they are valid HTML.
Values
- The name after
data-: lowercase letters, digits, hyphens (data-price-excl-vat); the browser converts uppercase letters to lowercase. - The value is always text – a script has to convert a number or JSON itself.
- In
datasetthe name is written withoutdata-and with capital letters instead of hyphens:data-price-excl-vat→dataset.priceExclVat.
- Applies to: all elements
- In JavaScript:
element.dataset
Examples
A button with product data and a style by state:
<button type="button" class="add" data-id="8590001" data-price="4.50" data-state="in-stock">Sourdough bread – add to cart</button> <button type="button" class="add" data-id="8590007" data-price="1.30" data-state="sold-out" disabled>Poppy seed cake – sold out</button>
.add[data-state="sold-out"] {
text-decoration: line-through;
}
Reading the data in a script:
<script>
document.querySelectorAll('.add').forEach(function (b) {
b.addEventListener('click', function () {
var price = Number(b.dataset.price); // "4.50" → 4.5
addToBasket(b.dataset.id, price);
});
});
</script>
Things to watch out for
- Anyone who views the source of the page can see the data in the attributes – nothing secret belongs in them. The server must not take the price from
data-priceas binding; the visitor can change it. - Search engines and screen readers do not know about the data – content for people belongs in the text.
- Values that have a meaning for HTML have their own attributes (
value,datetime,href) or elements (data,time).
Browser support
Works in all major browsers (web-features does not rate it for Baseline). Since version: Chrome 7, Firefox 6, Safari 5.1. As of October 2026 (MDN browser-compat-data).
Related:
data – machine-readable value
class – classes (attribute)
script – script
template – template