Lesson 49 of 55
HTMLCustom Data Attributes – `data-*`
9 min
Course progress89%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 49 of 55
HTML9 min
Keep these ideas in mind as you work through the lesson.
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>
data- and may contain letters, digits, hyphens, periods, and underscores.element.dataset; hyphens become camelCase (data-user-id → element.dataset.userId).data-category, data-index).<script type='application/json'> block or client‑side storage.data-*data-? ✅element.dataset in JavaScript? ✅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.