DevAcademy
LearnHTMLData Attributes
AdvancedHTML

Data Attributes

Learn how to store custom data directly on HTML elements using data-* attributes, and read them from JavaScript.

Reading Time

10 min

Lesson

Lesson 25 of 27

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>
Output

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

Try it yourself — edit and run

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>
Output

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.

Interview Questions

Quick Quiz

1. What prefix must a custom data attribute use?

2. Which JavaScript property provides access to an element’s data attributes?

3. Should sensitive information be stored in data attributes?