Quiz

What are `data-` attributes good for?

Topics
Web APIsHTMLTesting

TL;DR

data-* attributes attach small pieces of application-specific metadata to an element when no standard HTML attribute expresses the meaning. JavaScript reads and writes them through element.dataset. They are useful for component configuration, stable testing hooks, analytics labels, and IDs needed by event delegation, but they are strings in user-editable markup—not secrets, authorization state, or a replacement for a large application data model.


What are data- attributes good for?

Custom data attributes provide a standards-compliant bridge between HTML and code without inventing non-standard attributes.

Reading and writing values

A hyphenated attribute name maps to a camel-cased property on dataset:

<button type="button" data-product-id="sku-42" data-action="add-to-cart">
Add to cart
</button>
const button = document.querySelector('[data-action="add-to-cart"]');
console.log(button.dataset.productId); // "sku-42"
button.dataset.state = 'pending'; // Adds data-state="pending".

Values are exposed as strings. Parse numbers, booleans, or JSON explicitly and handle invalid input rather than relying on coercion.

Appropriate uses

  • Configure a reusable behavior directly from server-rendered markup.
  • Associate an element with an application identifier for event delegation.
  • Provide a stable data-testid when a test cannot locate an element by accessible role, label, or visible text.
  • Attach analytics metadata without reusing styling classes.
  • Integrate a library that defines a documented data-* convention.

When another mechanism is better

Use semantic elements and standard attributes first. For example, use disabled for an unavailable button and ARIA only when native HTML cannot express the accessibility semantics. Keep large or rapidly changing state in JavaScript or an external store rather than serializing it repeatedly into the DOM.

Anyone can inspect and modify the DOM, so never trust data-* values for permissions, prices, account identity, or security decisions. The server must validate any value that crosses a trust boundary. User editability is not a reason to avoid data-*; it is a reminder that client-side state is never authoritative.

Avoid using data attributes purely as styling hooks when a class communicates the styling role more clearly. Tests should prefer user-facing queries and use test IDs as a deliberate fallback.

Further reading

Exercises

Check your understanding
Beta
Check your understanding Exercise
Check your understanding Exercise

Which uses of data-* attributes are appropriate? Select all that apply.