Custom data attributes let you store extra information on any HTML element using attributes that start with data-. They are useful for tiny bits of configuration, JavaScript hooks, or labels that don’t belong in the visible content. In JavaScript, you read and write them via the dataset API.
Instead of hard-coding values in your JS, you can attach them directly to elements in HTML and keep your structure, styling, and behavior nicely connected.
data-name="value" (for example: data-user-id="42").dataset maps hyphenated names to camelCase: data-user-id → el.dataset.userId.Number() or JSON.parse().
<!-- HTML: custom data attributes -->
<button
id="buy-btn"
data-product-id="P-101"
data-price="299"
data-currency="INR">
Buy now
</button>
<!-- JS: reading via dataset -->
const btn = document.getElementById('buy-btn');
console.log(btn.dataset.productId); // "P-101"
console.log(Number(btn.dataset.price)); // 299 as a number
console.log(btn.dataset.currency); // "INR"
<!-- HTML: store config and metadata on elements -->
<div id="card" class="product"
data-product-id="P-101"
data-price="299"
data-stock="in"
data-tags="tea,organic">
Assam Tea
</div>
<!-- JS: read/write with dataset -->
<script>
const card = document.getElementById('card');
console.log(card.dataset.productId); // "P-101"
console.log(Number(card.dataset.price)); // 299 (number)
// Write updates
card.dataset.stock = 'out'; // sets attribute data-stock="out"
card.dataset.discountPercent = '10'; // creates data-discount-percent="10"
</script>
Use the buttons below to filter products and update their data-* attributes. The JavaScript reads and writes values through element.dataset.
(interactions will log here)
data-configdata-long-press-time) which becomes camelCase in JS (dataset.longPressTime).JSON.parse().data-*..product[data-stock="out"].data-rating and style [data-rating="5"] with a special “Top Rated” badge using CSS.data-theme on <html> and toggle light/dark modes by switching CSS variables in JavaScript.MutationObserver to watch for data-* changes on a node and log when attributes update.data-tags contain a chosen keyword.data-*) store small bits of extra information directly on HTML elements.dataset object using camelCase property names.data-* gives you a powerful way to tie behavior to your DOM.