data attribute
A custom HTML attribute whose name starts with data-, such as data-theme="dark", used to store extra information on an element.
In more detail
CSS can select on it with [data-theme="dark"] and JavaScript can read it through element.dataset. Setting data-theme on the root or on a section is a simple, fast way to switch themes for everything inside it.
Example
In the browser: An attribute like data-id="101" appears in JavaScript as element.dataset.id. Data attributes are handy for event delegation, testing hooks such as data-testid and theme switches such as data-theme="dark", which CSS can also select.Related terms
- theming — Giving the same components different looks, such as light, dark or a different brand, by swapping the token values they use.
- CSS custom property — A value you name yourself in CSS, such as --color-primary: #2563eb, and use elsewhere with var(--color-primary).
- HTML — The markup language that describes the structure and meaning of a web page with elements such as <button>, <input> and <h2>.
- HTML attribute — A name and value written inside a start tag, such as class="card" or hidden, that configures an element.
- event delegation — Handling events for many child elements with one listener on a shared ancestor, using event.target to find which child was involved.
Taught in
- CSS Custom Properties & Dynamic Theming Architecture — Design Systems & Component Engineering
- Dark Mode Strategies: System Preference, Class & High-Contrast — Design Systems & Component Engineering
- HTML Parsing, Tokenization And The Document Object Model (DOM) — Frontend Architecture & Web Platform
- Modern DOM Querying: querySelector, closest And matches — Frontend Architecture & Web Platform
- CSS Custom Properties: Scoping, Fallbacks And Theming — Frontend Architecture & Web Platform
- Event Delegation: Memory-Efficient Interaction Handlers — Frontend Architecture & Web Platform