HTML · The document layer
When should you use data attributes?
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.
<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>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.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1How do you read a data attribute in JavaScript?
- 2What type are data attribute values?
- 3Should data attributes be used for styling?
- 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.