HomeJAVASCRIPTWhat are data attributes?

What are data attributes?

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:

  1. 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.
  2. Syntax
    • Must start with data-.
    • Example: data-*data-name, data-product-id, data-role.
  3. Accessing Data Attributes
    • In JavaScript, you can access them via the dataset property:
    const btn = document.getElementById("btn1"); console.log(btn.dataset.userId); // "42" console.log(btn.dataset.role); // "admin"
    • Note: data-user-id becomes dataset.userId (camelCase conversion).
  4. 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.

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *