⚙️ Module 13 · HTML5 APIs🟡 IntermediateLESSON 43

Data Attributes

⏱️ 13 min read
📖 Theory + Code
🧩 5 Quiz Questions
🏗️ 1 Challenge
Course progress30%
🎯 What you'll learn: The data-* attribute syntax, reading and writing values via JavaScript's dataset property, and real-world use cases.

The data-* Syntax

Custom data attributes let you attach extra information to any HTML element without inventing non-standard attributes. Any attribute prefixed with data- is valid HTML and completely ignored by the browser's rendering — it's just there for your own JavaScript to read.

data-basic.html
HTML
<div class="product-card"
     data-product-id="482"
     data-in-stock="true">
  Wireless Mouse
</div>

Reading With dataset

JavaScript exposes every data-* attribute through the element's dataset property. Hyphenated names automatically convert to camelCase — data-product-id becomes dataset.productId.

data-dataset.html
HTML
<script>
// Reading
const card = document.querySelector('.product-card');
console.log(card.dataset.productId); // "482"
console.log(card.dataset.inStock);   // "true" (always a string!)

// Writing
card.dataset.productId = '999';
</script>
⚠️
Dataset values are always strings
Even data-in-stock="true" comes back as the string "true", not the boolean true. Convert explicitly when you need a real boolean or number.

Real Use Cases

Use caseExample
Storing a database ID on a DOM rowdata-user-id="1042"
Toggling states without extra classesdata-state="open"
CSS hooks via attribute selectors[data-theme="dark"] { ... }
Passing config to a JS widgetdata-autoplay="false" data-duration="5000"
💡
CSS can read data attributes too
Attribute selectors like [data-state="open"] let you style elements based on their data attribute, entirely without JavaScript.
🧩 Knowledge Check — Lesson 43
5 questions to test your understanding.
1. What prefix must a custom data attribute use?
2. How does data-product-id appear via dataset in JS?
3. What type is a dataset value always read as?
4. Can CSS read data attributes without JavaScript?
5. Does the browser render or style data-* attributes by default?
💪
Coding Challenge — Lesson 43
Apply what you learned · Intermediate Level
Challenge: Build a Filterable Card

Build a div with data-category="courses" and data-featured="true". Then write a JS snippet that logs both values via dataset.
💡 Show hints if you're stuck
  • Remember: dataset.featured returns the string "true", not a boolean.
Finished this lesson?
Mark it complete to track your progress.
🎉

Lesson 43 Complete!

You can now attach custom data to any element. Up next: the Drag and Drop API!

Lesson 43 of 62Module 13 — HTML5 APIs