Hack Frontend Community

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

<div data-user-id="1234" data-role="admin">Hello, this is Hack Frontend 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?

<button data-product-id="42">Buy</button>
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.