data-* attributes store custom data on elements. They are accessible via dataset in JavaScript (e.g., el.dataset.userId) and are useful for hooks without affecting semantics. Use data-* as lightweight hooks, but test parsing and accessibility, and avoid sensitive data.
What is the purpose of the data-* attribute?
Use guided tracks for structured prep, then practice company-specific question sets when you want targeted interview coverage.
Overview
The data-* attribute lets developers store custom information directly within HTML elements. These attributes are part of the HTML5 specification and are especially useful for passing small pieces of data to JavaScript without cluttering the DOM with nonstandard attributes.
Feature | Description |
|---|---|
Prefix | Always starts with |
Usage | Used to store metadata or temporary data tied to specific elements |
Access | Can be easily read or modified via JavaScript using |
Scope | Invisible to users, but part of the DOM and accessible in scripts |
Example: Adding and Accessing Custom Data
<button id="buy-btn" data-product-id="1234" data-price="49.99">Buy Now</button>
<script>
const button = document.getElementById('buy-btn');
console.log(button.dataset.productId); // '1234'
console.log(button.dataset.price); // '49.99'
</script>
In this example, the data-product-id and data-price attributes store product details that JavaScript can use when the user clicks the button.
Example: Dynamically Changing a Data Attribute
// Change the data attribute dynamically
button.dataset.price = '59.99';
console.log(button.dataset.price); // '59.99'
The dataset object provides a simple interface for updating or reading custom data attributes.
Common Use Cases
- Storing configuration values for UI components
- Passing identifiers or states to JavaScript functions
- Enhancing interactivity without additional hidden inputs
- Connecting frontend data to dynamic backend-rendered templates
Best Practices
- Use
data-*attributes for nonessential or UI-specific data only. - Do not store sensitive information — they are visible in the DOM.
- Keep names descriptive and lowercase with hyphens (e.g.,
data-user-role).
Practical scenario
You tag buttons with data-action so a single script can handle multiple actions.
Common pitfalls
- All dataset values are strings, requiring parsing.
- Inconsistent naming between HTML and JS (camelCase vs kebab).
- Storing sensitive data in the DOM.
Data attributes are lightweight but limited. Test parsing and ensure attributes do not leak secrets.
Think of data-* attributes as sticky notes on your HTML elements — small, hidden pieces of info that JavaScript can easily read or update.
- The
data-*attribute stores custom data on HTML elements. - Accessed in JavaScript via
element.dataset. - Useful for dynamic behavior, configuration, or metadata.
- Should not be used for sensitive or large-scale data.