#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
5 min read
•Question 6 of 49easy

What are data-* Attributes?

Storing custom data in HTML.

What You'll Learn

  • How to store custom data in HTML elements
  • Accessing data attributes with JavaScript
  • Common use cases

What are Data Attributes?

Data attributes let you store custom data directly on HTML elements. They start with data- followed by your custom name.

This is useful for storing information that JavaScript needs but doesn't belong in the visible content.

How to Use Them

index.htmlHTML
<article
  data-post-id="123"
  data-author="john"
  data-published="2024-01-15"
>
  <h2>Article Title</h2>
</article>

<button data-action="delete" data-item-id="456">
  Delete
</button>

Accessing in JavaScript

Use the dataset property. Note the naming conversion:

  • data-user-id in HTML becomes dataset.userId in JavaScript
  • kebab-case → camelCase
code.jsJavaScript
const article = document.querySelector('article');
console.log(article.dataset.postId);    // "123"
console.log(article.dataset.author);    // "john"
console.log(article.dataset.published); // "2024-01-15"

Common Use Cases

  1. API IDs - Store database IDs for AJAX calls
  2. Configuration - Store component settings
  3. Analytics - Track user interactions
  4. Dynamic Content - Pass data to JavaScript