HTMLintroevergreen

data-* attributes and dataset

Stash your own data on any element.

Custom data-* attributes let you attach arbitrary state to HTML, read and write it from JavaScript via the dataset API, and hook into it from CSS with attribute selectors and attr().

Any name you like, prefixed with data-

A data-* attribute is a valid HTML attribute whose name starts with data- and otherwise follows the rule: lowercase letters, digits, and dashes. <article data-author-id="42" data-status="draft"> is perfectly legal and ignored by the browser's own rendering β€” it exists purely for you. Use it to carry application state (an id, a status, a count) on the element it belongs to, instead of bolting on a parallel lookup table.

The dataset DOM API

In JavaScript every element exposes a dataset object β€” a live map of its data-* attributes. The key is the attribute name with the data- prefix stripped and the remaining dashes converted to camelCase: data-author-id becomes dataset.authorId. Reading el.dataset.status returns the current string value; assigning el.dataset.status = 'live' writes the attribute back to the DOM. Values are always strings, so parse with Number(...) when you need a number.

CSS hooks: attribute selectors and attr()

CSS can read data-* attributes too. Attribute selectors like [data-status="draft"] let you style elements by their data, turning an attribute into a state machine you drive from script. The attr() function pulls an attribute's value straight into content for generated text β€” content: attr(data-label) prints the label with no JavaScript at all.

Try it 4 examples

Style and label by data attribute

HTML+CSS+JSintro
Press Run to execute

Each <li> is colour-coded purely by its data-status value (green/gold/grey left borders, plus a faded "done" row) and prefixed with a gold DONE/WIP/TODO badge pulled from data-label via attr() β€” all driven by HTML data, with zero JavaScript.