Lesson 49 of 55 · HTML
Custom Data Attributes – `data-*`
Duration: 9 min
Custom Data Attributes – data-*
data-* attributes let you embed custom data in HTML without affecting semantics.
<button class='add-to-cart' data-product-id='12345' data-price='19.99'>Add to Cart</button>
<script>
document.querySelector('.add-to-cart').addEventListener('click', e => {
const btn = e.currentTarget;
const id = btn.dataset.productId;
const price = btn.dataset.price;
console.log(`Product ${id} costs $${price}`);
});
</script>
Rules
- Attribute name must start with
data-and may contain letters, digits, hyphens, periods, and underscores. - Access via
element.dataset; hyphens become camelCase (data-user-id→element.dataset.userId). - Values are always strings; convert to numbers or booleans as needed.
When to use
- Passing configuration or identifiers to JavaScript.
- Storing UI state that doesn’t affect rendering.
- For small, JSON‑like configuration objects (keep payloads tiny).
Best practices
- Keep data attributes small – avoid large blobs of JSON.
- Use meaningful names (
data-category,data-index). - For large structured data, consider a
<script type='application/json'>block or client‑side storage.
Quick checklist for data-*
- Attribute name starts with
data-? ✅ - Accessed via
element.datasetin JavaScript? ✅ - Values kept small and type‑converted as needed? ✅
- No critical UI logic relies solely on data attributes? ✅
- Fallback behaviour defined if JavaScript is disabled? ✅
Tip: When you need to expose a configuration object to many components, use a
<script type='application/json' id='config'>element and parse it once.