Junior
What is the recommended use of data attributes in HTML?
sobes.tech AI
Answer from AI
The data-* attributes in HTML are recommended for storing custom data that has no visual representation, directly within DOM elements. This allows:
- Storing small pieces of data related to the element: For example, product ID, element status, widget settings.
- Simplifying access and manipulation of data using JavaScript: Data can be easily accessed via
element.datasetand modified.
// Accessing data
const myElement = document.getElementById('my-element');
const elementId = myElement.dataset.elementId; // Getting the value of data-element-id
// Setting data
myElement.dataset.status = 'active'; // Setting the value of data-status
- Avoiding non-semantic classes: Using classes to store data (e.g.,
.status-active) can make markup less readable and harder to maintain. - Improving performance in some scenarios: Accessing data via
datasetcan be faster than parsing string attributes or working with hidden elements. - Using this data in CSS selectors:
/* Selecting elements with a specific status */
[data-status="active"] {
border: 1px solid green;
}
It is important to use data-* attributes for data that does not have another suitable HTML semantic attribute. For data that should be accessible to search engines or other parsers, appropriate semantic elements and attributes should be used.