Skip to main content

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:

javascript
<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).

javascript
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:

javascript
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 HTMLIn JS
data-user-iddataset.userId
data-product-namedataset.productName
data-is-activedataset.isActive

Why it is needed

Data attributes are often used when:

  1. You need to pass data to JS straight from HTML (for example, a product id).
  2. For initializing components or plugins.
  3. To handle events on elements without creating a separate data object.

Example: an "Add to cart" button

javascript
<button class="add-to-cart" data-id="42" data-name="Shirt">Add</button>
javascript
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 attributesData attributes
PurposeFor standard HTML propertiesFor custom data
SafetyCan conflict with standardsAlways safe
AccessThrough getAttribute()Through dataset
Examplehref, src, iddata-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 through element.dataset.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.