Intern
What are data-attributes?
sobes.tech AI
Answer from AI
Data attributes allow embedding arbitrary data into standard HTML elements without additional hacks, such as non-standard attributes. They are defined by the prefix data-, followed by any name containing only lowercase Latin letters, digits, hyphens, dots, colons, or underscores.
Access to data attribute values can be obtained through DOM Manipulation or CSS.
Example:
<div id="myElement" data-id="123" data-status="active"></div>
In JavaScript:
const element = document.getElementById('myElement');
// Access via dataset
console.log(element.dataset.id); // "123"
console.log(element.dataset.status); // "active"
// Access via getAttribute
console.log(element.getAttribute('data-id')); // "123"
In CSS:
[data-status="active"] {
border: 1px solid green;
}
Uses of data attributes:
- Storing data specific to the user interface.
- Transferring data from HTML to JavaScript.
- Defining element styles based on their data.
Advantages:
- Valid HTML5.
- Clear separation of content and presentation.
- Convenient access and manipulation of data.
Disadvantages:
- Not intended for storing large volumes of data.
- May be less performant compared to other methods in certain scenarios.