Sometimes an element needs to carry extra information that isn't meant for the user to see directly, but is meant for your own CSS or JavaScript to read. That's exactly what data attributes are for.
Any attribute name starting with data- is valid HTML and always safe to add — the browser ignores it visually, and never confuses it with a built-in attribute.
<article
id="post-33"
data-author-id="42"
data-category="frontend">
...
</article>Every data attribute is available on an element's dataset property, with the name converted to camelCase.
const article = document.querySelector('#post-33')
article.dataset.authorId // "42"
article.dataset.category // "frontend"A data attribute can also be selected and even displayed directly in CSS, using an attribute selector.
article[data-category="frontend"] {
border-left: 4px solid blue;
}Why not just make up an attribute
Data attributes are the standard way to attach custom information to an element — avoid inventing your own non-standard attribute names, which older browsers and validators may reject.