Learn how to use data-* attributes to store custom information on HTML elements and access it with JavaScript's dataset API.
HTML allows you to add custom attributes to any element by prefixing them with data-. These are called data attributes and provide a standard way to embed extra information in your markup.
<button data-action="delete" data-item-id="42">Delete</button>Data attributes:
data-* pattern is part of the specification.Data attribute names must follow these rules:
data-.| Attribute | Purpose |
|---|---|
data-id | Element identifier |
data-type | Element category/type |
data-status | Current state (active, disabled, etc.) |
data-tooltip | Tooltip text |
data-sort-key | Sorting value |
data-config | Configuration (JSON string) |
Keep names descriptive but concise. Use hyphens to separate words: data-user-role, not data-userrole.
JavaScript provides the dataset property on every element to read and write data attributes. Hyphenated names are converted to camelCase:
<div id="user" data-user-name="Alice" data-role="admin" data-login-count="5"></div>const el = document.getElementById('user');
// Read
console.log(el.dataset.userName); // "Alice"
console.log(el.dataset.role); // "admin"
console.log(el.dataset.loginCount); // "5" (always a string)
// Write
el.dataset.status = 'online'; // adds data-status="online"
// Delete
delete el.dataset.role; // removes data-role attributeNote that dataset values are always strings. Parse them with parseInt(), JSON.parse(), etc. as needed.
data-active="true", data-tab="settings"data-action="save" for event delegation[data-theme="dark"] { ... }data-price="29.99", data-category="books"aria-label, aria-expanded, etc.) instead.<!-- Product cards with data attributes -->
<div class="product-list">
<div class="card" data-product-id="101" data-category="electronics" data-price="299.99">
<h3>Wireless Headphones</h3>
<p>Price: $299.99</p>
<button data-action="add-to-cart" data-product-id="101">Add to Cart</button>
</div>
<div class="card" data-product-id="102" data-category="books" data-price="19.99">
<h3>HTML & CSS Guide</h3>
<p>Price: $19.99</p>
<button data-action="add-to-cart" data-product-id="102">Add to Cart</button>
</div>
</div>
<!-- CSS can target data attributes -->
<style>
[data-category="electronics"] { border-left: 3px solid #3498db; }
[data-category="books"] { border-left: 3px solid #2ecc71; }
</style>How do you access the `data-user-name` attribute in JavaScript?