Custom Data Attributes
Overview
Sometimes you need to store custom information inside an HTML element so that your JavaScript can easily read it later. For example, if you have a list of products, you might want to store the product ID directly on the product's `<div>`.
You cannot just invent your own HTML attributes (like `<div product-id="123">`) because it makes your HTML invalid. Instead, HTML5 gave us `data-*` attributes, allowing you to safely embed custom data right into the HTML.
Syntax
To create a custom attribute, it MUST start with `data-`, followed by whatever name you want (all lowercase). You can add as many data attributes as you want to a single element.
<!-- Storing the user ID and role directly in the HTML -->
<div data-user-id="98765" data-role="admin">
Welcome, Admin!
</div>
<!-- Storing product info on a button -->
<button data-product="shoes" data-price="2999">
Buy Now
</button>In JavaScript, you can easily read these values using the element's `dataset` property. Notice how the `data-` part is removed, and JavaScript converts dashes to camelCase (e.g., `data-user-id` becomes `userId`).
// Imagine we clicked the button from above
const button = document.querySelector('button');
// Access the dataset
const product = button.dataset.product; // "shoes"
const price = button.dataset.price; // "2999"
console.log(`Adding ${product} to cart for ₹${price}`);Common Pitfalls
- Never store highly sensitive information (like passwords or session tokens) in data attributes. Anyone can right-click, 'Inspect Element', and see them in plain text.
- Data attributes are always stored as strings. If you write data-count='5', JavaScript will read it as the string '5', not the number 5.
Real-World Example
Using data attributes to manage theme switching without complex JavaScript state:
<!-- The HTML stores the current theme -->
<html data-theme="dark">
<body>
<button onclick="toggleTheme()">Switch Theme</button>
</body>
</html>
<!-- CSS uses the data attribute to apply colors! -->
<style>
[data-theme="light"] { background: white; color: black; }
[data-theme="dark"] { background: black; color: white; }
</style>