Junior
What is the recommended use of data attributes in HTML?
sobes.tech AI
Answer from AI
data-* attributes are used to store arbitrary data associated with a specific HTML element, without the need to use custom attributes or DOM properties.
Main advantages:
- Semantic correctness: They are part of the HTML5 standard and do not violate document validity.
- Easy access: Data can be accessed through the
datasetproperty in JavaScript, which returns an object with keys corresponding to parts of the attribute afterdata-. - Convenience for JavaScript/CSS: They allow binding specific data to elements, which can then be used in JavaScript logic or for styling in CSS (using attribute selectors).
- Separation of data from presentation: They help separate the HTML structure from data that can be used for behavior or presentation.
Examples of usage:
- Storing record IDs in a database.
- Saving parameters for a popup or modal dialog.
- Defining the state of an element (e.g.,
data-state="active"). - Transferring small amounts of data from backend to frontend for use in JavaScript.
Example of access in JavaScript:
// HTML: <div id="myElement" data-id="123" data-category="electronics"></div>
const element = document.getElementById('myElement');
const id = element.dataset.id; // Accesses the value "123"
const category = element.dataset.category; // Accesses the value "electronics"