Sometimes an element needs to carry extra information that is not shown on the page: a product ID, a stock level, a category or a price used by a filter. HTML has a standard place for this: custom data attributes, any attribute whose name starts with data-. CSS can select and even display them, and JavaScript can read and change them through the dataset property.
In this lesson you will learn
- Writing valid
data-*attribute names - Selecting elements by data attribute in CSS
- Showing attribute values with
attr() - Reading and writing them in JavaScript with
dataset - When to use data attributes, and when not to
You should know elements and attributes and CSS selectors.
Data Attributes in CSS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>data-* attributes with CSS</title>
<style>
body { font-family: sans-serif; margin: 12px; font-size: 14px; }
.product { display: flex; align-items: center; padding: 8px 10px; border: 1px solid #ddd; border-radius: 6px; margin-bottom: 6px; max-width: 340px; }
.product span { margin-left: auto; }
/* Select by data attribute value */
.product[data-stock="out"] { opacity: 0.5; text-decoration: line-through; }
.product[data-stock="low"] { border-color: #fb8c00; }
/* Show an attribute's value as text with attr() */
.product[data-badge]::after {
content: attr(data-badge);
background: #e53935; color: white; font-size: 11px;
padding: 2px 6px; border-radius: 10px; margin-left: 8px;
}
/* Tooltip text stored in the HTML */
[data-tip] { position: relative; border-bottom: 1px dotted; cursor: help; }
[data-tip]:hover::after {
content: attr(data-tip); position: absolute; left: 0; top: 120%;
background: #263238; color: white; padding: 4px 8px; border-radius: 4px; white-space: nowrap; font-size: 12px;
}
</style>
</head>
<body>
<div class="product" data-id="p101" data-stock="in">Rice 5kg <span>410 taka</span></div>
<div class="product" data-id="p102" data-stock="low" data-badge="Only 3 left">Lentils 1kg <span>135 taka</span></div>
<div class="product" data-id="p103" data-stock="out">Tea 400g <span>240 taka</span></div>
<p>Hover over <span data-tip="Value Added Tax: 15%">VAT</span> to see a tooltip.</p>
</body>
</html>
Result
- A data attribute is any attribute named
data-followed by lowercase letters, digits or hyphens:data-id,data-stock,data-badge. Browsers ignore them, so they never clash with real HTML attributes. - Attribute selectors pick elements by value:
.product[data-stock="out"]fades the sold-out item, and[data-stock="low"]adds an orange border. [data-badge]without a value matches any element that has the attribute at all.content: attr(data-badge)shows the attribute’s text on the page through::after. The badge text lives in the HTML, so changing it needs no CSS changes.- The tooltip uses the same idea: hover over “VAT” and its
data-tiptext appears.
Data Attributes in JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>data-* attributes with JavaScript</title>
<style>
body { font-family: sans-serif; margin: 12px; font-size: 14px; }
.filters button { padding: 6px 10px; margin-right: 4px; border: 1px solid #999; background: white; border-radius: 6px; }
.filters button[aria-pressed="true"] { background: #1e88e5; color: white; border-color: #1e88e5; }
ul { padding-left: 18px; }
li[hidden] { display: none; }
#log { color: #555; font-size: 13px; }
</style>
</head>
<body>
<div class="filters">
<button data-filter="all" aria-pressed="false">All</button>
<button data-filter="fruit" aria-pressed="true">Fruit</button>
<button data-filter="veg" aria-pressed="false">Vegetables</button>
</div>
<ul id="list">
<li data-type="fruit" data-price-taka="120">Mango</li>
<li data-type="veg" data-price-taka="40">Potato</li>
<li data-type="fruit" data-price-taka="80">Guava</li>
<li data-type="veg" data-price-taka="60">Eggplant</li>
</ul>
<p id="log"></p>
<script>
const items = document.querySelectorAll("#list li");
function show(type) {
let total = 0;
items.forEach(li => {
// li.dataset.type reads data-type; data-price-taka becomes dataset.priceTaka
const match = type === "all" || li.dataset.type === type;
li.hidden = !match;
if (match) total += Number(li.dataset.priceTaka);
});
document.querySelectorAll("[data-filter]").forEach(b =>
b.setAttribute("aria-pressed", b.dataset.filter === type));
document.getElementById("log").textContent = `Showing ${type}: total ${total} taka`;
}
document.querySelectorAll("[data-filter]").forEach(b =>
b.addEventListener("click", () => show(b.dataset.filter)));
show("fruit");
</script>
</body>
</html>
Result
- Every element has a
datasetobject holding its data attributes.li.dataset.typereadsdata-type. - Names with hyphens become camelCase:
data-price-takais read asdataset.priceTaka. - Values are always strings, so the code uses
Number(...)before adding prices. - Each filter button stores its category in
data-filter, so one click handler serves all three buttons. aria-pressedtells screen readers which filter is active, and CSS uses it to colour the active button. Click the buttons to try it.- Selectors work in JavaScript too:
document.querySelectorAll("[data-filter]")finds every filter button.
| HTML | JavaScript | CSS selector |
|---|---|---|
data-id="p101" | el.dataset.id | [data-id="p101"] |
data-price-taka="120" | el.dataset.priceTaka | [data-price-taka] |
data-user-role="admin" | el.dataset.userRole | [data-user-role="admin"] |
When Not to Use Them
- If a standard attribute exists, use it:
hidden,disabled,aria-*,title,datetime. - Do not store important content only in data attributes. Search engines and some assistive tools ignore them, and text added with
attr()cannot be selected or copied. - Never put secrets in them, such as passwords or private prices. Anyone can read them with View Source.
Common Mistakes
- Using capital letters in the name, such as
data-userId. HTML lowercases it todata-userid, sodataset.userIdis undefined. Writedata-user-id. - Forgetting values are strings, so “40” + “80” becomes “4080”.
- Inventing non-standard attributes without the
data-prefix, such asstock="low", which is invalid HTML. - Putting key information only in an
attr()badge, where some users will miss it.
Practice Exercises
Exercise 1. Write CSS that gives any element with data-status="paid" a green left border and any with data-status="due" a red one.
Show answer
[data-status="paid"] { border-left: 4px solid #43a047; }
[data-status="due"] { border-left: 4px solid #e53935; }
Exercise 2. An element is <div id="cart" data-item-count="3">. Write JavaScript that adds 1 to the count.
Show answer
const cart = document.getElementById("cart");
cart.dataset.itemCount = Number(cart.dataset.itemCount) + 1; // now "4"
Assigning to dataset updates the HTML attribute, so CSS selectors that use it update too.
Frequently Asked Questions
Can I store JSON in a data attribute?
Yes, for small amounts: data-config='{"size":3}', read with JSON.parse(el.dataset.config). For larger data, a <script type="application/json"> block is cleaner.
Is attr() able to use numbers or colours?
Traditionally attr() only works inside content and returns text. Newer browsers are adding support for using it in other properties with a type, such as attr(data-size type(<length>)), but support is still limited.
Summary
data-*attributes store extra information on any element.- CSS selects them with
[data-name="value"]and can display them withattr(). - JavaScript reads and writes them through
dataset, with camelCase names and string values. - Prefer standard attributes when they exist, and never store secrets.
