Data Attributes
Data attributes let you store custom data on HTML elements using data-* attributes. JavaScript reads them with element.dataset.name. They keep data in HTML where it belongs — not scattered in JS variables.
Using Data Attributes
Example 1 — Product Cards with Data
<!-- Store product data directly on the element --> <div class="product-card" data-id="1042" data-price="299" data-category="electronics" data-in-stock="true" > <h3>Wireless Earbuds</h3> <button onclick="addToCart(this)">Add to Cart</button> </div> <!-- JavaScript reads: card.dataset.price = "299" --> <script> function addToCart(btn) { var card = btn.closest('.product-card'); var id = card.dataset.id; // "1042" var price = card.dataset.price; // "299" var cat = card.dataset.category; // "electronics" console.log('Added:', id, price, cat); } </script>
data-in-stock becomes dataset.inStock in JavaScript (kebab-case to camelCase). The value is always a string.
Data Attributes for Filtering
Example 2 — Filter Buttons
<button data-filter="all">All</button> <button data-filter="html">HTML</button> <button data-filter="css">CSS</button> <div class="lesson" data-topic="html">HTML Lesson 1</div> <div class="lesson" data-topic="css">CSS Lesson 1</div>
CSS can also target data attributes: [data-topic="html"] { border-color: red; } This makes interactive filtering possible without JavaScript in some cases.
data-* vs Hidden Inputs vs JS Variables
data-* keeps data attached to the element it belongs to — readable by both JS and CSS. Hidden inputs work but mix data with form semantics. JS variables work but lose their connection to the DOM element. data-* is the clean, modern approach.