5 min read
ā¢Question 6 of 49easyWhat 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-idin HTML becomesdataset.userIdin 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
- API IDs - Store database IDs for AJAX calls
- Configuration - Store component settings
- Analytics - Track user interactions
- Dynamic Content - Pass data to JavaScript