Ad space (banner)
🎨HTML & CSS Lessons
Lesson 19 / 50

Trying Out data Attributes (data-*)

In this lesson you'll learn how to attach custom data with data attributes, so you can understand how to switch appearance based on state. This is for people searching "HTML data attribute usage."

A data-* attribute is like a "tag" you can attach to an element carrying whatever information you like. Combined with the CSS attribute selector [data-status="done"], you can change how something looks based on its state.

The sample code specifies a different background color, via attribute selectors, for two kinds of tasks: data-status="done" and data-status="todo". Confirm how the appearance changes based on the value of data-status, even though both use the same .task class.

A common beginner stumbling block is how to name whatever comes after data-. Hyphen-separated kebab-case (like data-user-id) is the convention, and it's useful to also remember that it's automatically converted to camelCase (dataset.userId) when read from JavaScript.

This is often used in applications that switch state with JavaScript — a to-do list's "done/not done," or a tab's "currently selected" state, for example. As a way of managing data using a standard HTML feature, this is a style you'll see often in real projects.

HTML & CSS
OUTPUT

💡 The preview runs entirely on this page — nothing is sent externally.

Ad space (banner)
Ad space (in-article)