JavaScriptMedium
What is dataset?
element.dataset gives read/write access to an element's custom data-* attributes as a plain object, converting names from kebab-case in HTML (data-user-id) to camelCase in JavaScript (dataset.userId).
Rules
data-user-id="42"↔element.dataset.userId === "42".- Values are always strings. Convert them yourself:
Number(el.dataset.id),el.dataset.active === "true", orJSON.parsefor small JSON. - Setting
el.dataset.status = "done"addsdata-status="done"to the HTML. delete el.dataset.statusremoves the attribute."status" in el.datasetchecks for it.
Common uses
- Event delegation: store an id and action on the element (
data-id,data-action) and read them in one parent listener. - Configuration for widgets:
<div data-carousel data-interval="5000">. - CSS hooks: style with attribute selectors (
[data-state="open"]), which pairs nicely with state-driven UI. Libraries like Radix UI exposedata-statefor exactly this. - Passing server-rendered values to client scripts.
What not to store
- Sensitive data: it is visible in the HTML to anyone.
- Large or complex data: keep that in JavaScript (a
Mapkeyed by id). - Anything that duplicates state you already hold elsewhere and may go out of sync.
Code example
js
1document.body.innerHTML = `2 <style>[data-state="open"] { font-weight: bold; }</style>3 <button id="product" data-product-id="42" data-price="19.99" data-in-stock="true" data-state="closed">4 Add to cart5 </button>`;67const btn = document.getElementById("product");89console.log(btn.dataset); // { productId: "42", price: "19.99", inStock: "true", state: "closed" }10console.log(typeof btn.dataset.price); // "string" - always strings1112// Convert explicitly13const product = {14 id: Number(btn.dataset.productId),15 price: parseFloat(btn.dataset.price),16 inStock: btn.dataset.inStock === "true",17};18console.log(product); // { id: 42, price: 19.99, inStock: true }1920// Write and remove21btn.dataset.state = "open"; // CSS [data-state="open"] now applies22btn.dataset.lastClicked = "2026-11-17";23console.log(btn.getAttribute("data-last-clicked")); // "2026-11-17" (camelCase -> kebab-case)24delete btn.dataset.lastClicked;25console.log(btn.hasAttribute("data-last-clicked"), "state" in btn.dataset); // false true
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 JavaScript set.