Skip to the workspace
Pebellslearn by building
Grouping and Attributes  ›  Lesson

Data Attributes

Data Attributes 12 minA data-* attribute stores custom data on an HTML element for scripts or styles. It is visible in the document and is not a place for secrets or essential content that users need to read.

html / Data Attributes

Explore each scene at your own pace.

01 · The rule

The rule

Data Attributes

A data-* attribute stores custom data on an HTML element for scripts or styles. It is visible in the document and is not a place for secrets or essential content that users need to read.

Attach non-secret machine-readable data while keeping essential content accessible.

A script on a recipe page needs to know each recipe's cooking time so it can filter quick meals. The number is not something you want printed on every card, and there is no standard attribute called cooking-time. Inventing one would be invalid HTML. Data attributes are the official way to attach your own information to an element.

The rule

Your own attribute must start with data-.

Any attribute whose name begins with data- is valid on any element, and its meaning is up to you:

<article class="recipe" data-minutes="15" data-diet="vegan">
  <h3>Lemon Rice</h3>
  <p>Leftover rice, curry leaves, peanuts and lemon.</p>
</article>

The rules:

  • The name is data- followed by at least one character, in lowercase. Hyphens are fine: data-release-year.
  • The value is always text. data-minutes="15" holds the string "15", which a script must convert if it wants a number.
  • Browsers do nothing with them by themselves. They are storage for your code.

JavaScript can read them through the element's dataset, where hyphenated names turn into camelCase:

const card = document.querySelector(".recipe");
card.dataset.minutes;      // "15"
card.dataset.diet;         // "vegan"
// data-release-year would be card.dataset.releaseYear

CSS can select by them too, for example [data-diet="vegan"].

What data attributes are not for: content people need to read (put that in visible text), or anything secret. Everything in your HTML can be read by anyone through "View source".

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.