← Back to Chapters

Custom Data Attributes (data-*)

?️ Custom Data Attributes (data-*)

⚡ Quick Overview

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.

? Key Concepts

  • Syntax in HTML: data-name="value" (for example: data-user-id="42").
  • In JavaScript, dataset maps hyphenated names to camelCase: data-user-idel.dataset.userId.
  • All values are strings — convert to numbers/booleans yourself using Number() or JSON.parse().
  • Great for small bits of config, flags, and metadata tied to the DOM.
  • Not suitable for secrets, passwords, or huge JSON blobs (they are visible in the HTML).

? Syntax & Theory

? View Basic Syntax
<!-- 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"

? Example: HTML + JavaScript with data-*

? View Code Example
<!-- 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>

? Live Output / Interactive Example

?️ Interactive Demo

Use the buttons below to filter products and update their data-* attributes. The JavaScript reads and writes values through element.dataset.

Assam Tea
Headphones
Notebook

? dataset reads/writes log

(interactions will log here)

⚙️ JSON config in data-config

Box

 

? Tips & Best Practices

  • Naming: Use lowercase + hyphens in HTML (data-long-press-time) which becomes camelCase in JS (dataset.longPressTime).
  • Parsing: Convert strings to numbers/booleans yourself. For structured data, keep a small JSON string and call JSON.parse().
  • Security: Data attributes are visible to everyone — don’t store secrets, tokens, or personal data there.
  • Performance: Perfect for small flags/config. For large datasets, use JS variables, fetch calls, or a state store instead of data-*.
  • CSS hooks: You can style elements via attribute selectors, for example: .product[data-stock="out"].
  • Semantics: Use ARIA roles and semantic HTML for accessibility — custom data attributes don’t replace those.

? Try It Yourself

  • Create a card with data-rating and style [data-rating="5"] with a special “Top Rated” badge using CSS.
  • Add data-theme on <html> and toggle light/dark modes by switching CSS variables in JavaScript.
  • Attach a MutationObserver to watch for data-* changes on a node and log when attributes update.
  • Build a simple filter that shows only cards whose data-tags contain a chosen keyword.

? Summary

  • Custom data attributes (data-*) store small bits of extra information directly on HTML elements.
  • In JavaScript, you access them through the dataset object using camelCase property names.
  • All values are strings, so convert them when you need numbers, booleans, or structured objects.
  • They are great for configuration, flags, and JS hooks, but not for secrets or large data.
  • Combined with CSS attribute selectors and a bit of JS, data-* gives you a powerful way to tie behavior to your DOM.