data-* attributes store extra values on elements without an extra DOM nodes or backend requests.
Table of Content
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
idtitleclass
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?
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?
<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?
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
The HTML <pre> tag keeps the original format of your text. It shows spaces and line breaks exactly as you…
The br tag adds a single line break in HTML. It is an empty tag that does not need a…
HTML attributes add extra detail to elements so the browser knows how to handle them. Here you will see examples…
You use the <aside> tag to mark extra content in HTML. It does not replace the main text and shows…
The HTML <strong> tag shows strong importance. This tag gives semantic meaning to text. Screen readers and search engines recognize…
The script tag adds JavaScript to a web page in HTML. This lets the page run logic or load content.…
Paragraphs help group-related text. They build clear, readable pages. You use them to split ideas or topics. The HTML p…
The HTML tabindex Attribute lets you change the tab order on a web page. It helps control keyboard access. What…
Skip link in HTML helps users jump to important parts of a web page without delay. What is an HTML…
HTML form validation attributes help you check the form data before it reaches the server. What Are HTML Form Validation…