What Are Data Attributes?
Any attribute prefixed with data- is a custom data attribute. They let you attach extra information to an element without inventing new HTML attributes or relying on classes.
Data Attribute Example
<button data-user-id="42" data-role="admin">
Delete User
</button>Reading Data Attributes in JavaScript
The dataset property gives JavaScript easy access to every data-* attribute on an element, automatically converting kebab-case names to camelCase.
Reading with dataset
Console Output
Click “Run” to see the console output here.
Selecting with CSS Attribute Selectors
Data attributes can also be targeted directly in CSS using attribute selectors — useful for styling elements based on state without adding extra classes.
CSS Attribute Selector
<style>
[data-role="admin"] {
color: red;
}
</style>
<span data-role="admin">Admin</span>Common Use Cases
- Storing an ID that maps a DOM element to a backend record.
- Marking element state, like data-status="active".
- Passing configuration values to a JavaScript widget.
- Powering CSS-only interactions combined with attribute selectors.
Not for Sensitive Data
Data attributes are visible in the page source and can be read or modified by anyone using browser dev tools. Never store sensitive information, like tokens or personal data, in them.
Best Practice
Use data-* attributes as the standard way to bridge HTML and JavaScript without polluting class names with non-styling information.