What are HTML data attributes?
data-* attributes store custom data on HTML elements that JavaScript can read without using hidden inputs or class name hacks.
HTMLJavaScript
Overview
HTML5 `data-*` attributes let you attach arbitrary data to any element without affecting presentation. They are accessible via the `dataset` property in JavaScript and are useful for storing IDs, configuration, or state close to the element that needs it.
Key Points
- •Any attribute starting with `data-` is a custom data attribute: `data-user-id`, `data-color`.
- •JavaScript reads them via `element.dataset.userId` (camelCase conversion from `data-user-id`).
- •Values are always strings - parse numbers/booleans explicitly.
- •They are visible in the HTML source (do not store secrets there).
- •CSS can use them in attribute selectors: `[data-theme="dark"] { ... }`.
Examples
Store an ID on an element and read it in JS
html<button data-product-id="42" data-action="add-to-cart">
Add to Cart
</button>
<script>
document.querySelector('button').addEventListener('click', (e) => {
const id = e.currentTarget.dataset.productId; // "42" (string)
const action = e.currentTarget.dataset.action; // "add-to-cart"
console.log(id, action);
});
</script>Use data attributes for CSS theming
css[data-theme="dark"] {
background: #0f172a;
color: #f8fafc;
}
[data-size="lg"] .card {
padding: 2rem;
}Set and update data attributes via JS
javascriptconst el = document.getElementById('widget');
// Read
console.log(el.dataset.status); // "active"
// Write
el.dataset.status = 'inactive'; // sets data-status="inactive"
// Delete
delete el.dataset.status;
// Old-fashioned equivalent
el.setAttribute('data-status', 'active');
el.getAttribute('data-status');Pro Tip
Data attributes are the clean alternative to encoding data in class names (`.user-42`), hidden inputs, or global JS variables. They keep data and markup together, making event delegation patterns especially clean: one listener on a parent reads `event.target.dataset` to know which child was clicked.