HTML · The document layer

When should you use data attributes?

Mediumdata attributesdatasetjavascriptUpdated Oct 2026
Quiz this track

Short answer

Data attributes are custom data-* attributes for storing extra information on an element, read through the dataset API. They are not for styling hooks or sensitive data.

A data attribute lets you attach small pieces of metadata to an element without inventing a non-standard attribute. JavaScript reads them through the dataset property, which converts kebab-case names to camelCase.

html
<button data-action="save" data-item-id="42">Save</button>

<script>
  const button = document.querySelector("[data-action=save]");
  console.log(button.dataset.action);
  console.log(button.dataset.itemId);
</script>
data-item-id is read as dataset.itemId.

Good and bad uses

  • Good: identifiers, configuration values or state for a script
  • Good: a stable hook for querySelector
  • Bad: replacing semantic attributes such as href, value or aria-label
  • Bad: storing secrets or large data blobs that belong in a proper store
  • Bad: using data attributes as the primary styling API when a class would be clearer

Values are strings. If you need numbers, booleans or objects, convert them in JavaScript. Data attributes are visible in the DOM, so treat them as public.

The dataset API does not include attributes with uppercase letters, and the conversion is not fully reversible for unusual names. Prefer simple lowercase kebab-case names.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1How do you read a data attribute in JavaScript?
  2. 2What type are data attribute values?
  3. 3Should data attributes be used for styling?
  4. 4Why should secrets not go in data attributes?

Say it in the interview

Data attributes are for attaching small pieces of custom data to an element. I read them through dataset, which maps kebab-case to camelCase, and they are always strings. I use them for script configuration, identifiers or state. I do not use them for styling when a class is clearer, and I never put secrets there because they are visible in the DOM. If I need structured data, I keep it in JavaScript or a proper data store.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live HTML mock interview and get scored feedback on depth, clarity and confidence.