Data attributes
Carry component data with data-* attributes.
data-* attributes
Sometimes you want to attach custom data to an HTML element that JavaScript will read later. data-* attributes are made for that: <button data-action="copy">. You pick the name after the dash; the value is free-form text.
The browser does not ignore these attributes, but it does not give them a special meaning either. They are small data slots for JavaScript to read. So use data-* for behaviour, not for looks: carry which button does what, or which card stands for which record.
Reading and writing data-*
The browser exposes data-* attributes on the JavaScript side through the dataset collection. The data-user-id attribute is read as element.dataset.userId: dashes are dropped and the following letters go uppercase. The same rule applies when writing.
Pick short, meaningful names: data-id, data-action, data-target. They must not start with a number or a special character. You may leave the value empty, but a text or number is usually clearer. This group covers the HTML side only; the JavaScript side belongs to another lesson.
What data-* is not for
data-* attributes are small data slots, but not for everything. Look-and-feel (colour, size) belongs in CSS; reaching for data-colour is a bad habit. Accessibility data (description, state) belongs to aria-* attributes; you cannot carry screen-reader info in data-open.
Still, data-* is ideal for invisible but structural facts: which record a card represents, which panel a tab opens, which field a filter picks. JavaScript reads that data and wires behaviour to it. HTML first, behaviour second.
Exercise Write a card with data-*
Write an <article> inside body. Give it data-id="42" and data-category="garden". Inside it put a non-empty <h3> and an <a> link with data-action="open" and a non-empty href.
Show example solution
<body>
<article data-id="42" data-category="garden">
<h3>Rose Growing Guide</h3>
<a href="/posts/rose-guide" data-action="open">Open</a>
</article>
</body>
Test yourself
-
Which one is a valid data-* attribute?
- data 2 (has a space)
- data* (has an asterisk)
- data-toggle
- dataset (a JS property)
Show answer
data-toggle — Correct. A data-* attribute starts with the 'data-' prefix and is followed by a name.
-
Complete the data-* attribute
<button ____>Copy</button>Show answer
<button data-action="copy">Copy</button> -
Match each attribute to its purpose
- data-id
- Carries the record id
- data-action
- Carries the button task
- data-target
- Carries the target element
- data-index
- Carries the list order