HTML data-* Attribute

Beginner
⏱️ 5 min read
📚 Updated: Jun 2026
🎯 3 Examples
Custom Data

Introduction

The data-* attributes in HTML provide a way to store custom data private to the page or application. They let you attach extra information to any element without affecting how the page looks, and they are especially useful for JavaScript behavior and CSS styling hooks.

What You’ll Learn

01

data- prefix

Naming pattern.

02

Any element

Global usage.

03

dataset

JS access.

04

String values

DOM storage.

05

CSS hooks

[data-state].

06

vs data

Not object URL.

Purpose of data-*

The primary purpose of data-* attributes is to store custom metadata on HTML elements. This data is not shown to users by default and does not change standard rendering. It gives developers a standard, valid way to embed configuration, IDs, state flags, or other values that scripts need.

💡
Not the object data attribute

The standalone data attribute on <object> points to an external file URL. data-* custom attributes work on any element and store arbitrary string metadata.

📝 Syntax

Prefix the name with data- followed by a descriptive identifier:

data-*.html
<div data-example="custom-data">This element has custom data</div>



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

Syntax Rules

  • Name format: data- + your name (use lowercase and hyphens, e.g. data-user-id).
  • Do not use uppercase letters in the attribute name; browsers normalize them to lowercase.
  • Include at least one hyphen after data- (e.g. data-id) to avoid future conflicts with standard attributes.
  • Values are always stored as strings in the DOM.

How It Works

In the first example, data-example stores the string custom-data on the <div> element for scripts to read later.

💎 Values

The data-* attribute can hold different kinds of information, but the browser always treats the value as a string:

  • Textdata-role="admin"
  • Numbers as stringsdata-count="5" (parse with Number() in JS)
  • Booleans as stringsdata-active="true"
  • JSON as a stringdata-config='{"theme":"dark"}' then JSON.parse()
data-values.html
<div data-price="19.99" data-in-stock="true"></div>



<script>

  var el = document.querySelector("[data-price]");

  var price = parseFloat(el.dataset.price);

  var inStock = el.dataset.inStock === "true";

</script>

⚡ Quick Reference

HTML attributeJavaScript (dataset)Notes
data-user-id="123"el.dataset.userIdHyphens become camelCase
data-username="jane"el.dataset.username = "new"Set updates the attribute
getAttributeel.getAttribute("data-user-id")Alternative to dataset
CSS selector[data-state="open"]Style by data value
Removedelete el.dataset.userIdRemoves the attribute
Value typeAlways stringParse numbers/JSON in JS

Applicable Elements

ElementSupported?Notes
Any HTML elementYesGlobal custom data attributes
<div>, <button>, <li>YesCommon for UI state and config
<object data="...">Different featuredata is the resource URL, not data-*
Reserved namesNoDo not invent attributes that duplicate standard ones

data-* vs the object data attribute

Featuredata-*data on object
ElementsAny element<object> only
PurposeCustom metadataEmbedded file URL
JavaScriptelement.datasetobject.data
Exampledata-price="10"data="file.pdf"

Examples Gallery

User profile data, and reading or updating values with dataset.

Example

Let’s look at a simple example of how to use data-* attributes in HTML:

data-*.html
<div id="user" data-user-id="123" data-username="john_doe" data-email="john@example.com">

  <!-- Content for the user profile -->

</div>
Try It Yourself

How It Works

In this example, data-* attributes store user-related information such as user ID, username, and email. JavaScript can read these values without duplicating them in visible text.

Dynamic Values with JavaScript

You can dynamically set or retrieve data-* values using the dataset property:

dataset.html
<script>

  // Get the value of a data attribute

  var userId = document.getElementById("user").dataset.userId;



  // Set a new value

  document.getElementById("user").dataset.username = "new_username";

</script>
Try It Yourself

How It Works

The dataset property maps data-user-id to dataset.userId. Assigning to dataset.username updates the underlying data-username attribute in the DOM.

♿ Accessibility & Security

  • Not a substitute for visible text — Important information for users should still appear in content or ARIA, not only in data-* attributes.
  • Screen readers ignore data-* — They do not announce custom data attributes by default.
  • No secrets — Never store passwords, tokens, or private data in data-*; users can see them in DevTools.
  • Prefer semantic HTML — Use native elements and ARIA when conveying meaning to assistive tech.
  • Validate parsed JSON — If you store JSON in data-*, wrap JSON.parse in try/catch.

🧠 How data-* Works

1

Author adds data-*

Custom name and string value on any element.

Markup
2

Browser stores in DOM

Attributes appear in HTML and DevTools.

DOM
3

JS or CSS consumes data

dataset, getAttribute, or [data-*] selectors.

Use
=

Flexible metadata layer

Behavior and styling without invalid custom attributes.

Browser Support

Custom data-* attributes and the dataset API are supported in all modern browsers.

HTML5 · Fully supported

Universal custom data attributes

All major browsers support data-* markup and dataset.

99% Browser support
Google Chrome Fully supported
Full support
Mozilla Firefox Fully supported
Full support
Apple Safari Fully supported
Full support
Microsoft Edge Fully supported
Full support
data-* attributes & dataset 99% supported

Bottom line: Use data-* and dataset confidently in all modern projects.

💡 Best Practices

✅ Do

  • Use descriptive names like data-user-id or data-action
  • Use dataset for clean JavaScript access
  • Parse numbers and JSON explicitly in scripts
  • Use data-* for UI state hooks and component config
  • Keep names lowercase with hyphens

❌ Don’t

  • Store passwords, API keys, or sensitive data
  • Confuse data-* with object data URL attribute
  • Use uppercase letters in attribute names
  • Rely on data-* alone for critical user-facing info
  • Create non-standard attributes without the data- prefix
  • Choose meaningful and descriptive names for your custom data-* attributes to maintain clarity in your code.
  • Avoid storing sensitive or critical information in data-* attributes, as they are easily accessible through browser developer tools.
  • Use the dataset property in JavaScript to interact with data-* attributes efficiently.

Conclusion

The data-* attribute in HTML is a powerful tool for storing custom data within elements. It provides a flexible, standards-based way to pass configuration and state to JavaScript and CSS without breaking HTML validity.

Use it for non-sensitive metadata, pair it with dataset in scripts, and remember that values are always strings until you parse them. For embedding file URLs in <object>, use the separate data attribute instead.

Key Takeaways

Knowledge Unlocked

Five truths every developer should know about data-*

Bookmark these before adding custom attributes.

5
Core concepts
🌐 02

Any Element

Global scope.

HTML5
⚙️ 03

dataset

camelCase API.

JS
📝 04

String Values

Parse in JS.

Types
🔒 05

Not Private

No secrets.

Security

❓ Frequently Asked Questions

They are custom HTML attributes starting with data- that store extra string metadata on elements for JavaScript or CSS.
Use element.dataset.userId. Hyphenated names after data- become camelCase in dataset.
No. The data attribute on <object> is a resource URL. data-* stores custom metadata on any element.
Yes, as a string value. Read it with JSON.parse(element.dataset.config) and handle parse errors safely.
Yes. Use attribute selectors like [data-state="open"] or [data-theme="dark"].
No. They are visible in page source and DevTools. Do not store secrets in data-* attributes.

Store custom data on your elements

Practice data-* attributes and the dataset API with live Try It examples.

Try basic data-* example →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

3 people found this page helpful