Skip to main content
Practice Problems

What are data attributes in HTML

data attributes are a way to store custom data in HTML elements. They start with the data- prefix and allow safely passing information from HTML to JavaScript without creating non-standard attributes.


Syntax

html
<div data-user-id="1234" data-role="admin">Hello, this is IT Lead team!</div>

Where are they used?

  • To pass data to JavaScript
  • To initialize components
  • To store configurations
  • When working with events (e.g., a button can have data-id)
  • For event delegation (e.g., on lists)

How to get data attribute in JavaScript?

html
<button data-product-id="42">Buy</button>
javascript
const button = document.querySelector("button"); const productId = button.dataset.productId; console.log(productId); // "42"

All data- attributes become available through element.dataset, and the attribute name converts to camelCase.

Tip:

Use data attributes to store metadata directly in HTML — it's better than creating custom attributes or storing data in classes.

Short Answer

Interview ready
Premium

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

Finished reading?
Practice Problems