Data Attributes
HTML5 introduced data attributes — a way to store custom data directly on HTML elements. They start with data- followed by any name you choose. JavaScript reads them instantly without any extra variables.
Storing Data on Elements
<div class="lesson-card" data-lesson-id="6" data-xp="20" data-completed="false"> <h3>Images and Media</h3> </div>
Images and Media
Reading with JavaScript
<button id="buy" data-product-id="PRD-001" data-price="11" data-name="Chai Support"> Buy Now </button> <script> var btn = document.getElementById('buy'); btn.addEventListener('click', function() { // data-product-id becomes dataset.productId (camelCase) var id = btn.dataset.productId; var price = btn.dataset.price; var name = btn.dataset.name; alert(name + ' Rs.' + price); }); </script>
CSS Attribute Selectors
<style> [data-status="active"] { background: green; color: white; } [data-status="pending"] { background: orange; color: black; } [data-status="error"] { background: red; color: white; } </style> <span data-status="active">Active</span> <span data-status="pending">Pending</span> <span data-status="error">Error</span>
Data attributes power shopping cart item IDs, tooltip content, animation triggers, tab switchers, and click tracking in analytics — all without adding extra JavaScript variables or hidden inputs.
Before HTML5, developers stored custom data in rel attributes, hidden form inputs, or class names like class="product-id-123". HTML5 data attributes made this clean and officially standardized in 2014.