What are data-* attributes?
data-* attributes are a special mechanism in HTML that lets you store arbitrary data right in the markup, safely and conveniently.
What it is
Any attribute starting with data- is called a data attribute.
It can be used to store extra information tied to an element without creating custom attributes.
Example:
<div class="product" data-id="42" data-name="Shirt" data-price="4900"></div>How to access it in JavaScript
Every data-* attribute is automatically exposed on the
element.dataset object, with keys converted into properties (in camelCase).
const product = document.querySelector('.product');
console.log(product.dataset.id); // "42"
console.log(product.dataset.name); // "Shirt"
console.log(product.dataset.price); // "4900"How to change it
You can change it directly through dataset, and this updates the HTML attribute:
product.dataset.price = '5900';
console.log(product.getAttribute('data-price')); // "5900"Naming rules
- The attribute must start with
data- - After
data-comes any name (Latin letters, hyphens) - In JS, hyphens are converted into camelCase:
| In HTML | In JS |
|---|---|
data-user-id | dataset.userId |
data-product-name | dataset.productName |
data-is-active | dataset.isActive |
Why it is needed
Data attributes are often used when:
- You need to pass data to JS straight from HTML (for example, a product id).
- For initializing components or plugins.
- To handle events on elements without creating a separate data object.
Example: an "Add to cart" button
<button class="add-to-cart" data-id="42" data-name="Shirt">Add</button>document.querySelector('.add-to-cart').addEventListener('click', (e) => {
const { id, name } = e.target.dataset;
console.log(`Product ${name} (ID: ${id}) added to cart`);
});Difference from regular attributes
| Regular attributes | Data attributes | |
|---|---|---|
| Purpose | For standard HTML properties | For custom data |
| Safety | Can conflict with standards | Always safe |
| Access | Through getAttribute() | Through dataset |
| Example | href, src, id | data-user-id, data-price |
What not to store there:
- large JSON objects,
- sensitive data (passwords, tokens, and so on), because all of it is visible in the HTML and available to the user.
Summary
data-*attributes are a universal, safe and readable way to store small pieces of custom data in HTML and access them throughelement.dataset.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.