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

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