What are Data Attributes and When to Use Them?
Answer
Data attributes (data-*) allow you to store custom data on any HTML element, accessible via JavaScript and CSS without breaking HTML validity.
Syntax
<element data-[name]="value"></element>
How It Works
Examples
<!-- Storing user information -->
<div data-user-id="42" data-role="admin" data-created-at="2024-01-15">
User Card
</div>
<!-- Product data for e-commerce -->
<button
data-product-id="SKU-001"
data-price="29.99"
data-currency="USD"
class="add-to-cart"
>
Add to Cart
</button>
Accessing via JavaScript
const element = document.querySelector("[data-user-id]");
// Using dataset (recommended)
console.log(element.dataset.userId); // "42"
console.log(element.dataset.role); // "admin"
console.log(element.dataset.createdAt); // "2024-01-15"
// Note: kebab-case becomes camelCase
// data-user-id → dataset.userId
// Using getAttribute
console.log(element.getAttribute("data-user-id")); // "42"
// Setting data
element.dataset.status = "active";
// Creates: data-status="active"
Using in CSS
/* Style based on data attribute */
[data-role="admin"] {
border: 2px solid gold;
}
/* Show attribute value as content */
.badge::after {
content: attr(data-count);
}
/* Attribute selectors */
[data-status="active"] {
color: green;
}
[data-status="inactive"] {
color: gray;
}
[data-price] {
font-weight: bold;
}
Use Cases
| Use Case | Example |
|---|---|
| Configuration | data-config='{"theme":"dark"}' |
| State tracking | data-expanded="true" |
| Analytics | data-track="button-click" |
| Component data | data-tooltip="Help text" |
| Dynamic behavior | data-action="submit" |
Best Practices
<!-- ✅ Good: Descriptive, lowercase with hyphens -->
<div data-user-id="42" data-is-active="true">
<!-- ❌ Avoid: Storing sensitive data -->
<div data-password="secret123">
<!-- ❌ Avoid: Complex data (use JSON in JS instead) -->
<div data-complex="too,much,data,here">
<!-- ✅ Good: JSON for complex data -->
<div data-config='{"theme":"dark","size":"large"}'></div>
</div>
</div>
</div>
Key Points
- Prefix must be
data-followed by lowercase letters - Values are always strings (parse if needed)
- Perfect for JS frameworks and component data
- Don't use for styling that should be in CSS classes
- Avoid storing sensitive or large amounts of data