user
What is the data-something attribute in html?
alphonsio

Custom Data Attributes


The data-something attribute in HTML refers to custom data attributes, which are attributes that start with data- and are used to store extra information on HTML elements. These attributes are not displayed to the user but can be accessed via JavaScript or used for styling with CSS selectors in some cases.

Syntax

<div data-user-id="12345" data-role="admin">John Doe</div>

In this example:

  • data-user-id and data-role are custom data attributes.
  • You can name them anything, as long as they start with data-.

Accessing Data Attributes with JavaScript

const element = document.querySelector('div');
console.log(element.dataset.userId); // "12345"
console.log(element.dataset.role);   // "admin"

Note: The dataset property returns all data-* attributes as a JavaScript object, and the names are converted to camelCase.

Why Use data-* Attributes?

  • To attach data to elements without affecting their structure or appearance.
  • Useful for JavaScript-based interactions or storing metadata (like IDs, roles, categories, etc.).

Not for:

They should not be used for storing sensitive data, or replacing proper APIs, JSON data models, or database storage.

Let me know if you want a practical example or use case.