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", or JSON.parse for small JSON.
  • Setting el.dataset.status = "done" adds data-status="done" to the HTML.
  • delete el.dataset.status removes the attribute.
  • "status" in el.dataset checks 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 expose data-state for 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 Map keyed 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 cart
5 </button>`;
6
7const btn = document.getElementById("product");
8
9console.log(btn.dataset); // { productId: "42", price: "19.99", inStock: "true", state: "closed" }
10console.log(typeof btn.dataset.price); // "string" - always strings
11
12// Convert explicitly
13const 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 }
19
20// Write and remove
21btn.dataset.state = "open"; // CSS [data-state="open"] now applies
22btn.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.

Open in study app