Chuyển đến nội dung

Bài 77 · Interactive Elements

Custom Data Attributes

Store your own data on HTML elements with data-* attributes, read and write it through JavaScript's dataset, and style elements with CSS attribute selectors.

Sometimes an element needs to carry a little extra information that no standard attribute covers: the ID of the product a button adds to the cart, the price of a menu item, the current state of a widget. You could invent your own attribute, like price="4.50", but that's invalid HTML, and a future version of the language might give that name a different meaning.

HTML reserves a whole family of attribute names for exactly this purpose: custom data attributes, which start with data-. They're valid on every element, browsers ignore them for display, and both JavaScript and CSS can read them easily.

Writing data attributes

A data attribute is any attribute whose name starts with data- followed by at least one more character:

HTML
<button data-product-id="A-1042" data-price="18.90" data-in-stock>
  Add to cart
</button>

The rules for the name are short:

  • It must start with data- and have something after the hyphen.
  • Use lowercase letters, digits and hyphens. HTML lowercases attribute names anyway, so data-productId turns into data-productid.
  • Don't use colons or spaces. (A few other characters are technically allowed, but simple names are easiest to work with.)

The value is always a string. data-price="18.90" stores the text "18.90", not a number, and an attribute written without a value, like data-in-stock above, has the empty string as its value.

Data attributes are for data that belongs to your own page and scripts. If a standard attribute or element already expresses the meaning, use that instead: <time datetime>, <data value>, hidden, disabled or an ARIA attribute will always be understood by browsers and assistive technology, while data-* is understood only by your code.

Reading and writing with dataset

In JavaScript, every element has a dataset property that gives you all of its data attributes as an object. The names are converted from hyphens to camelCase: the hyphen disappears and the next letter becomes uppercase.

HTML attribute JavaScript property
data-price element.dataset.price
data-product-id element.dataset.productId
data-in-stock element.dataset.inStock
Reading data with dataset

Notice Number(button.dataset.price). Because the value is a string, adding it directly would glue text together ("02.40") instead of doing arithmetic. Convert values to the type you need: Number() for numbers, value === "true" for yes/no flags, and JSON.parse() if you stored JSON.

This example also uses one listener on the list instead of one per button. That pattern, called event delegation, works well with data attributes: each button carries its own data, and a single function handles them all. See Event Attributes and Event Listeners for more on listeners.

Writing works the same way, in reverse:

JavaScript
const card = document.querySelector(".card");

card.dataset.status = "archived";      // adds data-status="archived"
card.dataset.lastSeen = "2026-05-01";  // adds data-last-seen="2026-05-01"
delete card.dataset.status;            // removes data-status

Assigning to dataset converts camelCase back to a hyphenated attribute name, and anything you assign is turned into a string. card.dataset.count = 3 stores "3".

You can still use the general attribute methods if you prefer, with the full attribute name: getAttribute("data-price"), setAttribute("data-price", "4.10"), hasAttribute("data-in-stock") and removeAttribute("data-price"). You'll meet these again in The Document Object Model.

Styling with attribute selectors

CSS can select elements by their data attributes, which makes them a neat way to drive styles from state:

Selector Matches
[data-status] Any element with a data-status attribute
[data-status="done"] Elements whose data-status is exactly done
[data-tags~="urgent"] Elements whose space-separated data-tags list contains urgent
[data-size^="x"] Values that start with x

When JavaScript changes the attribute, the matching styles update automatically.

Styling state with data attributes

The attr() function in the ::after rule pulls the attribute's value into generated content, so each task displays its own status. Generated text like this is decorative: it can't be selected and isn't reliably read by screen readers, so don't put essential information there.

Accessibility note. These task rows are plain <div> elements, which is fine for a quick visual demo. A real task list should use <button> elements (or checkboxes) so keyboard and screen-reader users can operate it too. Data attributes add data; they never add meaning or behavior for assistive technology.

Practical uses

Here are situations where data attributes shine:

  • Connecting HTML to JavaScript. Mark the elements a script should enhance with data-* hooks, such as data-copy-target="#code-1" on a "Copy" button. Using data attributes instead of classes keeps styling and behavior separate: a designer can rename classes without breaking scripts.
  • Passing configuration. A carousel might read data-interval="5000" and data-autoplay="false" to set itself up.
  • Tracking state that CSS reacts to, as in the task list above (data-state="open", data-theme="dark").
  • Storing IDs and small values that a click handler needs, like data-product-id or data-row-index.
  • Testing. Many teams add data-testid attributes so automated tests can find elements without depending on text or styling.

And a few situations where they don't:

  • Large amounts of data. Long JSON strings in attributes make the HTML heavy and awkward. Use a <script type="application/json"> block or load the data with JavaScript.
  • Anything secret. Data attributes are visible to anyone who views the page source.
  • Meaning for machines. Search engines and screen readers ignore data-*. Use semantic elements, ARIA or structured data instead.
  • Content. Text the reader needs belongs in the element, not in an attribute.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Which JavaScript expression reads the attribute data-user-name?

    dataset converts the hyphenated part after data- to camelCase: user-name becomes userName.
  2. 2. An element has data-count="5". What does element.dataset.count + 1 produce?

    Data attribute values are always strings, so + joins text. Use Number(element.dataset.count) + 1 to get 6.
  3. 3. Which CSS selector matches only elements whose data-state is exactly open?

    Attribute selectors use square brackets. [data-state="open"] matches the exact value.
  4. 4. When should you NOT use a data attribute?

    Everything in the HTML, including data attributes, is visible to anyone who opens the page source.

Summary

  • Custom data attributes start with data- and are valid on every element.
  • Names should be lowercase; values are always strings.
  • In JavaScript, element.dataset maps data-product-id to dataset.productId; assigning adds the attribute and delete removes it.
  • CSS attribute selectors like [data-status="done"] style elements by their data, and attr() can display a value in generated content.
  • Use data attributes for script hooks, configuration and state; use standard elements, ARIA or structured data when you need meaning.

Next lesson: Templates and Web Components.

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.