DATA8 min20 XP

Data Attributes

Learn Data Attributes with live examples, interactive editor, and Shiv AI code review.

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.

CIWeb HTML Course • 22 Lessons • Free

Explain with Analogies

Shiv AI explains this lesson using real-life analogies.

Click Explain tab to generate.
index.html
Preview
Write code then click Deep Analyze

How do you access data-user-id="42" in JavaScript?

Explanationdataset converts kebab-case to camelCase: data-user-id becomes dataset.userId. This is the modern way. getAttribute("data-user-id") also works but dataset is cleaner and more readable.
Build Challenge
Data Attribute Cards
Build at least 2 product or lesson cards using data-* attributes. Include a button that reads and displays the data.
Requirements (5 to pass)
data attributes
multiple data attrs
dataset in js
button
script
solution.html
Preview
Community Wall
Lesson 17
0/500
0/20 lines
as
Recent Posts
Lesson 17
AI
Shiv AI
Online