In HTML, data attributes are custom attributes that let you store extra information on standard HTML elements without using non-standard attributes or cluttering class names.
They start with data- followed by your own attribute name. For example:
<button id="btn1" data-user-id="42" data-role="admin">
Click Me
</button>
Key Points:
- Custom Data Storage
- You can use them to store additional information directly in HTML, useful for JavaScript.
- Example:
data-user-id="42"stores the user ID.
- Syntax
- Must start with
data-. - Example:
data-*→data-name,data-product-id,data-role.
- Must start with
- Accessing Data Attributes
- In JavaScript, you can access them via the
datasetproperty:
const btn = document.getElementById("btn1"); console.log(btn.dataset.userId); // "42" console.log(btn.dataset.role); // "admin"- Note:
data-user-idbecomesdataset.userId(camelCase conversion).
- In JavaScript, you can access them via the
- Use Cases
- Attaching metadata (IDs, roles, states) without making extra API calls.
- Passing small bits of configuration or state to JavaScript.
- Useful for dynamic UI elements (e.g., product IDs in a shopping cart).
✅ Good practice: Use data attributes for small amounts of data. For large or complex data, use JSON or APIs.
