HTML & CSSEasy
What is a data-* attribute?
data-* attributes let you store custom, private data on any HTML element, for example data-user-id="42" or data-state="open". JavaScript reads them through the element.dataset object (with names converted to camelCase), and CSS can target them with attribute selectors.
Rules
- The name after
data-must be lowercase and may contain hyphens:data-product-sku. - Values are always strings; convert numbers and booleans yourself (
Number(el.dataset.price)). el.dataset.productSkumaps todata-product-sku(hyphens become camelCase).- Setting
el.dataset.state = "open"writes the attribute;delete el.dataset.stateremoves it.
Common uses
- Attach IDs or config to elements for event delegation: one click listener on a list reads
event.target.closest("[data-id]"). - Styling hooks for state:
[data-state="open"] { ... }(used heavily by Radix UI and shadcn/ui). - Test selectors:
data-testidfor stable end-to-end tests. - Passing server-rendered config to scripts.
What not to do
- Do not store sensitive data; it is visible in the page source.
- Do not use them for data that has a proper attribute or element (
value,<time datetime>, ARIA states). - Avoid storing large JSON blobs; use a
<script type="application/json">block instead.
Interview tip
Mention event delegation with dataset; it shows you know how to scale event handling without one listener per element.
Code example
html
1<style>2 body { font-family: system-ui; }3 li { padding: 6px; cursor: pointer; }4 li[data-in-stock="false"] { color: #9ca3af; text-decoration: line-through; }5 li[data-selected] { background: #ffd84d; }6</style>7<ul id="products">8 <li data-id="p1" data-price="19.99" data-in-stock="true">Mug</li>9 <li data-id="p2" data-price="34.50" data-in-stock="false">Hoodie</li>10 <li data-id="p3" data-price="8.00" data-in-stock="true">Sticker pack</li>11</ul>12<p id="out">Click a product</p>13<script>14 // One listener for every item (event delegation)15 document.getElementById("products").addEventListener("click", (e) => {16 const li = e.target.closest("li[data-id]");17 if (!li) return;18 document.querySelectorAll("[data-selected]").forEach((el) => delete el.dataset.selected);19 li.dataset.selected = ""; // adds data-selected=""20 const price = Number(li.dataset.price); // strings -> number21 const inStock = li.dataset.inStock === "true"; // data-in-stock -> inStock22 document.getElementById("out").textContent =23 `${li.dataset.id}: $${price.toFixed(2)} ${inStock ? "available" : "sold out"}`;24 });25</script>
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the HTML & CSS set.