Code Snippets
/

HTML Data Attributes, Highlight, and Media Elements

HTML Data Attributes, Highlight, and Media Elements

Three HTML features people forget about: `data-*` attributes for stashing state and config on elements (queryable from CSS and JS), the semantic-highlight elements (`<mark>`, `<dfn>`, `<kbd>`, `<samp>`, `<var>`) that newcomers reach for `<span>` instead, and the HTML5 media elements (`<video>`, `<audio>`, `<source>`, `<track>`) with their key attributes. Treat this as a reference; you do not need to memorize it.

HTML
Easy
3 snippets
html-attributes
html-elements
html-media

355 views

5

<!-- data-* attributes attach arbitrary key-value pairs to any element.
     They are valid HTML, queryable from CSS via [data-foo="..."], and exposed
     to JavaScript on the element's .dataset property as a kebab-to-camel map. -->

<button id="toggle" data-state="closed" data-target="#menu">
    Toggle menu
</button>

<nav id="menu" data-state="closed">
    <a href="/">Home</a>
    <a href="/about">About</a>
</nav>

<!-- CSS can react to data-state changes without any class swapping. -->
<style>
[data-state="open"] {
    display: block;
}

[data-state="closed"] {
    display: none;
}
</style>

<!-- JavaScript reads and writes via element.dataset. The HTML attribute
     data-user-id becomes element.dataset.userId in JS (kebab -> camel). -->
<script>
const btn = document.getElementById('toggle');
const menu = document.getElementById('menu');
btn.addEventListener('click', () => {
    const next = menu.dataset.state === 'open' ? 'closed' : 'open';
    btn.dataset.state = next;
    menu.dataset.state = next;
});
</script>

data-* attributes are the standard place to put per-element state and configuration: a card's data-card-id, a tab's data-active, a button's data-target. They are valid HTML, do not collide with future spec additions, and round-trip cleanly between CSS attribute selectors and the JavaScript element.dataset API. The naming convention is kebab-case in HTML (data-user-id) and camelCase in JS (element.dataset.userId). Use them for state machines and small config; do not abuse them for large blobs of JSON, since attributes are strings and parsing on every read is wasteful (use a <script type="application/json"> tag for that).