🌱BeginnerAttributes and Accessibility

Data Attributes

Store custom data in HTML elements with data-* attributes and access them from JavaScript.

Overview

Data attributes let you embed custom data directly in HTML elements without using non-standard attributes or external data structures. Any attribute that starts with data- followed by a descriptive name is a valid data attribute. Syntax: data-anything="value" Data attributes are: - Valid HTML (don't break validation) - Accessible via JavaScript (element.dataset.anything) - Accessible via CSS (attr(data-anything)) - Perfect for connecting HTML elements to JavaScript behavior

Key Points

  • •data-* attributes can be added to any HTML element
  • •The name after data- can use lowercase letters, numbers, and hyphens
  • •Access in JS via element.dataset camelCase conversion: data-item-id → dataset.itemId
  • •Values are always strings parse to number/boolean if needed in JavaScript
  • •Use for passing configuration to JS components, storing state, or binding data
  • •CSS can read data attribute values with attr() (limited use only for content)

Examples

Basic data attribute usage

<button
  data-product-id="42"
  data-product-name="Widget Pro"
  data-price="29.99"
  onclick="addToCart(this)"
>
  Add to Cart
</button>

<script>
function addToCart(button) {
  const id = button.dataset.productId;     // "42"
  const name = button.dataset.productName; // "Widget Pro"
  const price = parseFloat(button.dataset.price); // 29.99
  console.log(id, name, price);
}
</script>

Using data attributes for tab state

<div class="tabs">
  <button data-tab="home" class="active">Home</button>
  <button data-tab="profile">Profile</button>
  <button data-tab="settings">Settings</button>
</div>

<div data-panel="home">Home content</div>
<div data-panel="profile" hidden>Profile content</div>
<div data-panel="settings" hidden>Settings content</div>

Reading data attributes in JavaScript

const card = document.querySelector('[data-user-id="123"]');

// Read
const userId = card.dataset.userId;       // "123"

// Write
card.dataset.status = "active";           // sets data-status="active"

// Delete
delete card.dataset.status;               // removes data-status

Common Mistakes

  • Using uppercase letters in data attribute names they must be lowercase
  • Forgetting that dataset values are always strings parseInt() if you need a number
  • Storing sensitive data in data attributes they are visible in the page source

Note

Data attributes are perfect for JavaScript hooks. Instead of using id or class to identify elements for JS behavior, use data attributes this separates presentation concerns (class) from behavior concerns (data-*).

Exercises

Write HTML to solve each exercise. Use Preview to see it render in a live iframe, then mark as done.

Loading editor…

Completed: 0 / 5 exercises

Knowledge Check

Question 1 of 4

What is the correct syntax for a custom data attribute storing a user ID of 42?