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 lang Attribute: How it Works with Examples

The HTML lang attribute tells browsers and tools what language the page uses. It helps users and search engines understand…

HTML code Tag: How to Mark Up Code Snippets

The <code> tag in HTML shows short code, command names, or output. Use it to display text that 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 s Tag: How it Works with Examples

The HTML s tag places a line across text that has no longer value or does not hold importance. It…

HTML Heading Elements: Understanding h1 to h6 with Examples

The heading elements define a content structure in HTML. Use <h1> to <h6> to show levels. <h1> means the main…

How to Use sub Tag for Subscript Text in HTML

The sub tag in HTML shows text in subscript form. It places the text slightly below the normal baseline of…

HTML wbr Tag: Word Break Opportunities

The <wbr> tag in HTML helps the browser decide where it can break a word. It does not force a…

HTML source Tag: How to Embed Media with Examples

The source tag in HTML helps load different media formats and screen sizes. You can use it inside many other…

HTML Mark Tag: How to Highlight Text

The mark tag highlights text in HTML and shows that the text has relevance in the content. It adds a…

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…

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.