Sometimes you need to attach extra information to an element that HTML has no attribute for: a product id, a price, a state. That is what data-* attributes are for. You choose the name after data-.
<button data-book-id="42" data-price="14">Add The Slow Garden</button>
<script>
document.querySelector("button").addEventListener("click", function () {
this.textContent = "Added book " + this.dataset.bookId + " for $" + this.dataset.price;
});
</script>
Reading them in JavaScript
JavaScript exposes them through dataset. The name data-book-id becomes dataset.bookId: hyphens turn into camelCase.
Using them in CSS
[data-status="sold-out"] { opacity: .5; }
Rules
- Names are lowercase and use hyphens:
data-user-id. - Values are always text. Convert to numbers in JavaScript when needed.
- Do not store secrets. Anyone can read them with View source.
- Do not use them for content visitors need to read. Put that in real elements.
Prefer them to made-up attributes
<div price="14"> is invalid HTML. data-price is valid and future proof.