Leverage the attributes that work everywhere and store your own data in the HTML.
Open this lesson in KodokonSome attributes work on any element: these are the global attributes. You already use id and class; add to your toolbox hidden (hides the element), lang (indicates the language of a passage), title (tooltip on hover) and tabindex (keyboard focus order).
<p lang="en" title="Original quote">
Stay hungry, stay foolish.
</p>
<div hidden id="cookie-banner" class="banner">
We use cookies.
</div>Need to attach your own data to an element? Never invent a made-up attribute: HTML reserves the data-* attributes for exactly that. You choose the name after the dash, in lowercase kebab-case. Typical use cases: a product identifier, a UI state, a component configuration.
<article
class="product-card"
data-product-id="42"
data-category="books"
data-in-stock="true"
>
<h2>HTML for pros</h2>
</article>On the JavaScript side, these attributes are read through the dataset property. Watch out for the automatic conversion: the HTML kebab-case becomes camelCase in JavaScript. So data-product-id is read with dataset.productId. The values are always strings, even "true" or "42".
const card = document.querySelector(".product-card");
console.log(card.dataset.productId); // "42"
console.log(card.dataset.inStock); // "true"
card.dataset.state = "selected";