HTML Data Attributes with Examples

HTML Data Attributes with Examples

data-* attributes store extra values on elements without an extra DOM nodes or backend requests.

What are data-* attributes in HTML?

HTML allows custom data to live in elements. These values do not affect the layout. They help front-end code work without backend changes.

Each one begins with data-. You can add your own name after that dash. The browser ignores these by default.

Write the name with data- then use a word with no space. Also, you can use dashes between words. But, do not start with numbers or use capital letters.

<div data-user-id="42"></div>

You cannot use something like “data-UserId” or “data-42value“. That doesn’t follow the rule. You can use dashes, not camelCase or numbers at the start.

Here is a valid tag:

<div data-item-type="book"></div>

Here is an invalid tag:

<div data-Item-Type="book"></div>

The browser does not treat data-* like normal attributes. You need JavaScript to read them. Use .dataset to access them in JavaScript.

<div id="user" data-user-name="Ali"></div>

<script>
  let user = document.getElementById("user");
  console.log(user.dataset.userName); // prints "Ali"
</script>

Replace dashes with camelCase when you access the value.

Also, you can pass data directly into the element. You don’t need to store it somewhere else. That helps you to avoid global variables and avoid hardcoded logic in JavaScript.

Use it when you need to add extra data for behavior, not layout. It can work in HTML templates and dynamic elements.

Here is the use case:

  • Mark list items with sort order
  • Show tooltips from data stored in HTML
  • Pass IDs or types to modal buttons
  • Toggle features or states in UI

HTML data- Attributes vs. Global Attributes

Global attributes work across all elements. They include

  • id
  • title
  • class

And more.

data-* attributes do not change the way HTML styles or works directly. They only add extra info for scripts or styles.

The global attributes can be used for layout or logic while the data-* can be used when you need info that changes or comes from code.

JavaScript and DOM Integration

JavaScript works well with data-* because it reads them.

element.dataset.key = "value";

You can add them in JS or read them from HTML. It fits any script logic that needs hidden or custom info.

DOM libraries and frameworks also support these. You can loop through .dataset or use data for logic without APIs.

How to Style Elements with Data Attributes

Here is an example for how to use it as a selector in css:

div[data-status="active"] {
  color: green;
}

That adds style when a certain value matches. It does not need a class or ID. This keeps your CSS focused and avoids too many classes.

Examples

Toggle Button with data-status:

<button id="toggle" data-status="off">Switch</button>

<script>
  let btn = document.getElementById("toggle");
  btn.addEventListener("click", function () {
    let status = btn.dataset.status;
    btn.dataset.status = status === "off" ? "on" : "off";
    btn.textContent = "Switch (" + btn.dataset.status + ")";
  });
</script>

This button switches its status each time you click it. It uses data-status to change text without extra variables.

Product List with data-category Filter:

<ul>
  <li data-category="book">Book 1</li>
  <li data-category="movie">Movie 1</li>
  <li data-category="book">Book 2</li>
</ul>

You can build a filter with one data-category per item and change what is visible.

Form Field with data-error Message:

<input id="email" type="text" data-error="Please enter a valid email.">
<button onclick="validate()">Submit</button>

<script>
  function validate() {
    let input = document.getElementById("email");
    if (!input.value.includes("@")) {
      alert(input.dataset.error);
    }
  }
</script>

This script reads error or warning only if needed.

CSS Style by Data Value:

<div data-state="warning">Low Battery</div>

<style>
  [data-state="warning"] {
    background: yellow;
  }

  [data-state="error"] {
    background: red;
  }
</style>

The element color changes based on data. No class is needed. You can update the data-state value, and the style updates with it.

Wrapping Up

In this article, you learned how to use data-* attributes and how to access them in scripts. You also saw how they help with styling and logic.

Here is a quick recap:

  • You write them with a data- prefix.
  • You use dashes in names.
  • JavaScript reads them with .dataset.
  • CSS can style them by value.
  • Use them when you need extra data inside your HTML but want to keep your code simple.

FAQs

How to use <data-* attributes> in HTML with JavaScript?

HTML data attributes allow you to store extra information directly on HTML elements. You can access them using JavaScript via the dataset property. Example:

<div id="user" data-user-id="42" data-role="admin">User Info</div>

<script>
  const userElement = document.getElementById("user");
  const userId = userElement.dataset.userId;
  const role = userElement.dataset.role;
  console.log(userId); // Outputs: 42
  console.log(role);   // Outputs: admin
</script>

Can I use <data-* attributes> to pass values to CSS?

Yes, you can use data attributes as selectors in CSS. They help apply styles conditionally based on values. Example:

<button data-status="active">Submit</button>

<style>
  button[data-status="active"] {
    background-color: green;
    color: white;
  }
</style>

What is the correct syntax for <data attributes> in HTML?

The correct syntax follows the format data-name="value", where name can only include lowercase letters, numbers, dashes. Example:

<div data-product-id="1234" data-category="books">Book Details</div>
JavaScript Access:

const el = document.querySelector('[data-product-id]');
console.log(el.dataset.productId); // "1234"
console.log(el.dataset.category);  // "books"

Similar Reads

HTML title Attribute: How it Works with Examples

The HTML title attribute adds extra info to any element. You can use it to show tooltips on hover. What…

The em Tag in HTML: How to Emphasize Text in HTML

The HTML em tag shows stress or emphasis in text. It changes meaning for readers and screen readers. What is…

HTML Textarea Tag: How it Works with Examples

The HTML textarea tag gives users space to enter longer messages. This element helps build forms that accept feedback, comments,…

HTML data Tag: Machine-Readable Data

The data tag connects visible content with a machine-readable value in HTML. This helps browsers and tools understand and process…

HTML del Tag: How to Mark Deleted Text in Pages

The HTML del tag shows text that a user or author removed from a page. A browser shows this text…

HTML details Tag: How to Toggle Hidden Content

The <details> tag hides content and shows it when needed. It helps organize long pages. The tag shows extra info…

HTML meta Tags for SEO

In this article, you will learn what HTML meta tags are and how they work. You also see how they…

HTML Element: Everything You Need To Know with Examples

An HTML element builds every part of a web page. It holds the text or block you want the browser…

HTML Document Structure: How to Create DOCTYPE in HTML

The DOCTYPE ensures that your HTML is readable by browsers and ensures that pages follow modern standards. Understand the DOCTYPE…

HTML template Tag: How it Works with Examples

The HTML <template> tag lets you store HTML content that won’t show up right away. JavaScript can pull it in…

Previous Article

HTML ARIA Attributes for Accessibility

Next Article

HTML id Attribute: How to Assign Unique Identifiers to Elements

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.