data-* Attributes
Overview
Sometimes you need to store custom, application-specific data directly on an HTML element so your JavaScript or CSS can access it later. However, creating completely fake HTML attributes (like <div product-id="12">) is strictly invalid and breaks HTML parsing. HTML5 introduced data-* attributes as the official, standard way to embed custom data natively. These attributes are completely ignored by the browser's visual engine, but are effortlessly accessible via JavaScript's native dataset API.
Syntax
<!--
We attach custom 'data-' attributes to hold information
that JavaScript will need when the user clicks the button.
-->
<button
class="add-to-cart"
data-product-id="99102"
data-price="49.99"
data-category="electronics"
>
Add to Cart
</button>
<script>
const btn = document.querySelector('.add-to-cart');
// The 'dataset' object automatically strips the 'data-' prefix
// and converts kebab-case to camelCase!
console.log(btn.dataset.productId); // "99102"
console.log(btn.dataset.price); // "49.99"
</script>Common Pitfalls
- Storing highly sensitive data (like
data-user-password="1234") in data attributes. Data attributes are physically written into the HTML text payload, meaning anyone can right-click, 'Inspect Element', and see the data. - Using capital letters in the HTML attribute name (e.g.,
data-productId="12"). HTML attributes are strictly case-insensitive. You must use kebab-case (data-product-id), which JavaScript will automatically magically transform into camelCase (dataset.productId).
Interview Questions
data-* attributes directly inside your CSS?You can use the attr() CSS function or attribute selectors. For example: .add-to-cart::after { content: attr(data-price); } will literally print the price into the UI using only CSS.
Real-World Example
Managing a Dark/Light theme toggle entirely via data attributes.
<!-- By setting a data attribute on the root HTML tag... -->
<html data-theme="dark">
<style>
/* ...we can universally switch the color palette using CSS variables! */
html[data-theme="dark"] {
--bg-color: #000;
--text-color: #fff;
}
html[data-theme="light"] {
--bg-color: #fff;
--text-color: #000;
}
body { background: var(--bg-color); color: var(--text-color); }
</style>
</html>Check Your Knowledge
Test your understanding of data-* Attributes with these quick questions.