Skip to content

07. Data Attributes and Standard Attributes

HTML provides standard attributes that work on most elements, as well as custom data-* attributes for storing extra information. Understanding standard attributes and data attributes helps create more functional, maintainable HTML. Data attributes are particularly useful for JavaScript interactions and storing metadata.

Work on all elements:

<div id="content" class="container" title="Tooltip text" lang="en">
Content
</div>
  • id: Unique identifier
  • class: CSS class names
  • style: Inline styles
  • title: Tooltip text
  • lang: Language
  • hidden: Hide element
  • tabindex: Tab order
<div data-user-id="123" data-role="admin">Content</div>
const element = document.querySelector('div');
console.log(element.dataset.userId); // "123"
console.log(element.dataset.role); // "admin"
<article data-author="John Doe" data-published="2024-01-15">
Content
</article>
<button data-action="delete" data-item-id="456">Delete</button>
<div data-testid="user-profile">Profile</div>
<!-- Good: Standard attributes -->
<div id="content" class="container" title="Description">
<!-- Avoid: Data attributes when standard works -->
<div data-id="content" data-class="container">
<!-- Good: Meaningful names -->
<div data-product-id="123" data-category="electronics">
<!-- Avoid: Generic names -->
<div data-id="123" data-cat="electronics">