Data Attributes
Use data attributes to store custom information on elements.
Learning Goals
The Core Concept
Data attributes let you store custom data on HTML elements without using non-standard attributes. They start with 'data-' followed by your custom name. For example: <div data-user-id="42"></div>
Data attributes are:
- Valid HTML
- Accessible via JavaScript
- Ignored by browsers
- Perfect for JavaScript interactions
- Searchable in your code
You can store any information you need JavaScript to access. User IDs, action types, configuration values - anything. Then JavaScript can read these values using element.dataset.
For example: HTML: <button data-action="delete" data-id="123">Delete</button> JavaScript: button.dataset.action // returns "delete"
Data attributes keep your HTML clean and semantic. You're not misusing attributes meant for other purposes. This approach separates content (HTML) from logic (JavaScript).
Visual guide
Html concept flow
A simple original diagram to connect the lesson idea with real project flow.
Code & Implementation
<!-- Data attributes in HTML -->
<div class="product" data-product-id="456" data-category="electronics" data-price="99.99">
<h3>Product Name</h3>
<p>Product description</p>
</div>
<!-- With buttons -->
<button data-action="buy" data-product-id="456">Buy Now</button>
<button data-action="cart" data-product-id="456">Add to Cart</button>
<!-- Accessing in JavaScript (example) -->
<script>
const button = document.querySelector('button[data-action="buy"]');
const productId = button.dataset.productId; // "456"
const action = button.dataset.action; // "buy"
</script>Expected Output
Rendered preview: - Main heading: Data Attributes - Intro text block is visible - Layout follows clean documentation spacing
Practical Project: Data Attributes Implementation
Hands-on practice task
The Challenge
Apply your knowledge of Data Attributes to build a real-world feature. This project helps you move beyond theory and understand how HTML works in professional settings.
Helpful Hints
- •Refer back to the 'Steps' section for the correct sequence.
- •Check the 'Tips' for common optimization patterns.
- •Look at the 'Code Highlights' to ensure you're using the right syntax.
Quick Knowledge Check
What is data attributes in HTML?
Is data attributes difficult for beginners?
How should I practice data attributes daily?
Why is this topic important for real projects?
Continue Learning
Next steps after this lesson
Apply your knowledge of Data Attributes to build a real-world feature. This project helps you move beyond theory and understand how HTML works in professional settings.
Ready to put your coding skills to the test?
Don't just read—write code! Use our free Try-Code Playground to experiment with real-time preview, or search utilities on our Developer Tools List.