HTML5 Data Attributes
Attach custom data to elements with data-* attributes, and read it back from CSS and JavaScript.
読了時間 1 分
Sometimes you need to attach information to an element that isn't covered by any standard attribute — a database ID, a flag for JavaScript to check, a value CSS should style differently. data-* attributes exist exactly for this.
Basic usage
<button data-product-id="482" data-in-stock="true">Add to Cart</button>Any attribute name starting with data- is valid, custom, and guaranteed never to collide with a future built-in HTML attribute — which is exactly why the prefix exists.
Reading data attributes in JavaScript
<button id="add-btn" data-product-id="482" data-in-stock="true">Add to Cart</button>const button = document.getElementById("add-btn");
console.log(button.dataset.productId); // "482"
console.log(button.dataset.inStock); // "true" — always a stringThe dataset API automatically converts data-product-id into camelCase dataset.productId. Every value comes back as a string, even "true" or "482" — you're responsible for converting to a number or boolean if you need one.
Using data attributes in CSS
<div class="status" data-state="error">Something went wrong</div>.status[data-state="error"] {
color: red;
border-left: 3px solid red;
}
.status[data-state="success"] {
color: green;
border-left: 3px solid green;
}Attribute selectors let CSS style an element differently based on a data-* value — a common pattern for state-driven styling (loading, error, success) without needing a different class for every combination.
When to use data-* vs. a class
Use a data-* attribute for information — a value your code needs to read (an ID, a state, a config option). Use a class for styling hooks and grouping. It's common to see both on the same element, each doing its own job:
<li class="task-item" data-task-id="17" data-completed="false">
Buy groceries
</li>A word of caution
data-* attributes are visible in the page's HTML source — never store sensitive information (auth tokens, private user data) in one. Treat them the same as any other client-visible value.