Q22: What are custom data attributes (data-*) and how are they accessed in JavaScript?

Custom data attributes (data-*) allow embedding custom metadata directly on standard HTML elements without violating HTML specifications. In JavaScript, these values are accessed via the element's .dataset DOM property or using getAttribute(). In CSS, they are selected via attribute selectors [data-state='active'].

Custom Data Attributes Usage
<button id="userBtn" data-user-id="9876" data-role="admin">User Profile</button>

<script>
  const btn = document.getElementById('userBtn');
  console.log(btn.dataset.userId); // Output: "9876"
  console.log(btn.dataset.role);   // Output: "admin"
</script>

data-user-id converts to camelCase dataset.userId inside JavaScript.

Key Takeaways
  • Store arbitrary custom data formatted as data-attribute-name.

  • Read and write values in JavaScript via element.dataset.attributeName.

Knowledge Check

How does the HTML attribute data-user-role map into JavaScript's dataset object?