Middle+
What are custom data-attributes in HTML? How are they written, how to access them from JavaScript, and what are they used for?
sobes.tech AI
Answer from AI
Custom data attributes in HTML are special attributes that start with data- and allow storing arbitrary user data directly in HTML elements. They are used to pass additional information that does not affect the display but can be useful for scripts.
How to write:
<div data-user-id="123" data-role="admin">User</div>
How to access from JavaScript:
You can access them via the dataset property of the element, where attribute names after data- are converted from kebab-case to camelCase:
const div = document.querySelector('div');
console.log(div.dataset.userId); // "123"
console.log(div.dataset.role); // "admin"
What they are used for:
- Storing data related to the element without needing to create additional data structures.
- Convenience for passing parameters to scripts.
- Used in various UI libraries and frameworks for configuring component behavior.
Thus, data-attributes are a simple and standardized way to store user data in the DOM.