Sobes.tech
Junior

What are data attributes used for in HTML?

sobes.tech AI

Answer from AI

The data-* attributes are used to store custom data that has no visual representation directly in HTML elements.

Main purposes of use:

  • Access to data via JavaScript/CSS: They allow easy retrieval and manipulation of element data through JavaScript (element.dataset) or using them in CSS selectors ([data-attribute="value"]).
  • Storing metadata: Convenient for storing additional information related to the element (e.g., product ID, user type, state).
  • Creating custom components: They can be used to define behavior or properties of custom components implemented with JavaScript.
  • Enhancing semantics: They can add a certain level of semantics, describing specific data related to the content.

Example of usage in HTML:

<div data-product-id="123" data-category="electronics">
  Smartphone
</div>

Access via JavaScript:

// Getting the element
const productElement = document.querySelector('div');

// Accessing data attributes
const productId = productElement.dataset.productId; // 123
const category = productElement.dataset.category;   // electronics

Using in CSS:

/* Style for elements with data-category="electronics" */
[data-category="electronics"] {
  border: 1px solid blue;
}