liveBook · Manning

Dataset

As explained in Vanilla Web

A DOM property that exposes an element’s data-* attributes through a camelCase-keyed object of string values.

Use `dataset` to attach small amounts of application metadata to an HTML element without inventing new attributes. It exposes the element’s `data-*` attributes as string-valued properties: `data-user-name` becomes `dataset.userName`. Changes work both ways—setting a dataset property updates the attribute, and changing the attribute updates the dataset value. section 6.2.11 section 6.2.8

Set a behavior hook

```js const button = document.createElement("button"); button.dataset.action = "save"; button.innerText = "Save"; document.body.append(button); console.log(button.dataset.action); // "save" ``` The assignment also sets `data-action` on the button. That attribute is visible in DevTools. section 6.2.1 section 6.2.11

Keep the metadata contract small:

  • Use data attributes for IDs, behavior hooks, flags, or tiny configurations. Values remain strings; keep complex state in memory rather than storing large JSON blobs in markup. section 6.2.11
  • For a custom element’s core configuration, prefer standard attributes such as `variant` or `size`. Reserve `data-*` for application-specific metadata such as `data-product-id`; access standard custom-element attributes with `getAttribute` and `setAttribute`. section 7.9.1

How Vanilla Web covers it

How deep it goes
Explains string values, kebab-case-to-camelCase naming, and two-way attribute updates, but does not develop a complex state model.
Examples
Creates a button with `dataset.action`, reads it back, and contrasts metadata such as `data-product-id` with standard configuration attributes.
What it assumes
Introduces the data-attribute naming conversion while assuming familiarity with HTML elements and JavaScript property access.
What you can do after
Operate/configure element metadata through dataset and choose standard attributes instead for a custom element’s core configuration.
How it connects
Connects dataset to HTML data attributes, DOM attribute reflection, HTMLElement, and custom-element API design.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Vanilla Web. The section links point to the parts of the book it draws on.