Data Attributes and Per-Element State
Every element in a document already has somewhere to put state: its attributes. The data namespace formalises that, giving you an unlimited set of custom slots that are legal in the markup, visible in the inspector, serialisable when the page is copied, and readable from both JavaScript and CSS. That last property is what separates a data attribute from a property hanging off a JavaScript object keyed by element reference, which disappears the moment the node is replaced.
The pattern shows up in three shapes. Configuration, where a container declares the endpoint and page size its children should use. State, where a row records whether it is selected or expanded. And wiring, where a control carries the identifier that a delegated handler needs to act on. All three share the same virtue: the value lives on the element it describes, so removing the element removes the state with it.
What you gain over the alternatives:
- persistence across innerHTML round trips, since attributes travel with the markup
- a single source of truth that JavaScript, CSS, and tests can all read
- no event bus or global registry required to find a widget's configuration
- serialisation for free when the markup is stored, emailed, or diffed
- inspection in dev tools, where the attribute is right next to the element it configures
Reading and Writing Through dataset
The dataset property mirrors the attributes with a name translation: dashes are removed and the following letter is uppercased. Assigning to a dataset key writes the attribute, and removing the key removes the attribute, so the two representations never disagree.
<section
id="feed"
data-api-url="/api/items"
data-page-size="20"
data-cache-seconds="60"
data-empty-message="No results yet">
</section>
<script>
const feed = document.getElementById('feed');
// Read: data-api-url becomes apiUrl, data-page-size becomes pageSize.
const url = feed.dataset.apiUrl;
const size = Number(feed.dataset.pageSize) || 10;
const ttl = Number(feed.dataset.cacheSeconds) || 0;
// Write: the attribute is created or updated for you.
feed.dataset.pageNumber = '1';
feed.dataset.loading = 'true';
// Delete: removeAttribute is called under the hood.
delete feed.dataset.loading;
async function loadPage() {
const page = Number(feed.dataset.pageNumber) || 1;
const target = `${url}?page=${page}&size=${size}`;
try {
const response = await fetch(target, {
headers: ttl ? { 'x-cache-ttl': String(ttl) } : {}
});
const items = await response.json();
render(items);
feed.dataset.state = items.length ? 'ready' : 'empty';
} catch (error) {
feed.dataset.state = 'error';
feed.dataset.emptyMessage = 'Could not reach the server.';
} finally {
feed.dataset.loading = 'false';
}
}
</script>
Everything in the dataset is a string, and that is the detail that produces the most surprising bugs. An empty attribute reads as an empty string rather than true, so a test written as if (el.dataset.selected) fails on the very markup meant to satisfy it. Use el.hasAttribute('data-selected') when presence is the meaning, and reserve the dataset value for data you actually read.
đValues survive a round trip, properties do not
State kept on a JavaScript object keyed by node is lost when a re-render replaces that node. Attributes are written into the markup, so cloning, diffing, or re-parsing the HTML carries the value forward with no coordination code.
Attributes Versus Properties: Knowing the Difference
Data attributes have no such split, but the distinction matters the moment you work with built-in controls, and it explains several otherwise baffling bugs. The attribute is the declaration that appears in the markup: it is what the parser reads, what cloneNode copies, and what the initial property value is derived from. The property is the live value on the JavaScript object: it changes as the user interacts, and it is not written back to the attribute.
Consider a checkbox that a template renders as checked. The attribute says checked; the property says true. If script then unticks it, the property becomes false while the attribute still reads checked, and a clone made at that moment renders as checked because cloning copies attributes rather than properties. Form reset restores the property from the attribute, which is the behaviour that makes the split visible to users.
The rule that keeps you out of trouble: read the current state from the property, read the declared default from the attribute, and never assume the two agree after the page has been interactive for more than a second. Custom data attributes avoid the whole problem because nothing updates them behind your back.
Naming Rules and the Case Trap
The attribute name must start with data followed by a dash. After that, letters, digits, and dashes are legal, and the browser's translation between the two spellings has specific rules that are easy to trip over.
| Attribute | dataset key | Note |
|---|---|---|
data-page-size | pageSize | The dash before size triggers capitalisation |
data-api-url | apiUrl | Same rule, applied at each dash |
data-item2-id | item2Id | Digits are left alone by the translation |
data-user-id-2 | userId2 | A segment starting with a digit is not capitalised |
data-XMLData | xmlData | HTML parsers lowercase the attribute name first |
data- alone | Not exposed | The name must continue after the dash |
Two practical consequences follow. First, write the attribute names in lowercase with dashes and let the translation produce camelCase keys; mixed case in the markup is normalised by the parser before your script ever sees it, so the key you get may not be the key you wrote. Second, remember that a character is capitalised only when it is an ASCII letter sitting immediately after a dash, which is why digits and already-capitalised letters behave differently from what a quick reading of the rule suggests. If a key feels ambiguous, rename it rather than testing your memory of the rule.
Event Delegation Driven by Attributes
A list that re-renders every few seconds is the classic case for delegation, and the attribute is what makes the handler able to identify its target without a closure per row. One listener on the container survives every replacement of its children.
<ul id="tasks" data-endpoint="/api/tasks">
<li data-task-id="101" data-status="open">
Draft the migration plan
<button type="button" data-action="complete">Done</button>
</li>
<li data-task-id="102" data-status="blocked">
Review the rollback script
<button type="button" data-action="complete">Done</button>
</li>
</ul>
<script>
const list = document.getElementById('tasks');
list.addEventListener('click', async (event) => {
const button = event.target.closest('[data-action]');
if (!button) return;
const row = button.closest('li[data-task-id]');
const id = row.dataset.taskId;
const action = button.dataset.action;
if (action === 'complete') {
row.dataset.status = 'done';
button.disabled = true;
await fetch(`${list.dataset.endpoint}/${id}`, {
method: 'PATCH',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ status: 'done' })
}).catch(() => {
row.dataset.status = 'open';
button.disabled = false;
});
}
});
</script>
The rollback in the catch block is deliberate. Because the optimistic update wrote the new state into the attribute before the request, a failed request has exactly one place to undo it, and the UI and the attribute stay consistent whether the round trip succeeds or fails.
Styling From Attributes
Attributes are first-class styling hooks, which is useful when the state is meaningful to the visual design but should not be encoded in a class name. Attribute selectors match on presence, on exact value, and on value contained in a space-separated list, covering the three most common shapes of state.
li[data-status="open"] { border-left: 3px solid #f59e0b; }
li[data-status="done"] { opacity: 0.6; text-decoration: line-through; }
li[data-action]:hover { cursor: pointer; }
[data-state="loading"]::after {
content: "";
display: inline-block;
width: 12px;
height: 12px;
margin-left: 6px;
border: 2px solid #cbd5e1;
border-top-color: #2563eb;
border-radius: 50%;
animation: spin 700ms linear infinite;
}
[data-selected] { background: #eff6ff; }
@keyframes spin { to { transform: rotate(360deg); } }
One performance note: attribute selectors participate in the same style recalculation as class selectors, so there is no cost to preferring them. What does cost is selecting on a high-churn attribute such as a continuously updated progress value across a large subtree, because each change invalidates matching for every element under the nearest shared ancestor.
Keeping Attributes in Sync With Server State
When rows are rendered from an API response, the attributes on each row are a client-side copy of server truth. Treat them as a cache with an explicit revision rather than as an independent record. A data-rev attribute carrying the version or timestamp the server returned lets an optimistic update detect that it raced a change made elsewhere: if the response revision is older than the one on the row, discard the local result and re-fetch instead of overwriting newer data. The same discipline applies after any mutation. Write the new status into the attribute only once the server confirms, or write it immediately and roll it back in the failure path, exactly as the request handler above does. Either direction is fine as long as the attribute and the visible label are updated together, because users read the mismatch long before they open the inspector, and a test asserting one while the UI shows the other is worse than no attribute at all.
When a Data Attribute Is the Wrong Tool
Attributes are strings in a serialised document, and that is the wrong medium for anything that changes at animation-frame frequency, holds a reference to another object, or must never be visible to a user who opens dev tools. A slider position written to a data attribute on every pointer move triggers attribute change, style invalidation, and inspector updates for no benefit; keep the number in a variable and write the attribute only when the interaction ends.
Security-sensitive values do not belong there either. Anything in the markup is readable by any script on the page and is shipped to the client in plain sight, so a token, an internal identifier, or a permission flag should live in memory or in a cookie with appropriate flags instead.
The final boundary is duplication. If the same value already exists as a class, as a text node, or as a property the element exposes natively, a parallel data attribute creates a second source of truth that will drift. Derive rather than store, and reserve the namespace for state that exists nowhere else.
Common Mistakes
Testing an empty attribute as a truthy value
Fix: Use hasAttribute when presence carries the meaning; dataset reads an empty attribute as an empty string.
Writing camelCase directly into the attribute name
Fix: Keep names lowercase with dashes and let the browser translate them into camelCase dataset keys.
Updating a data attribute on every pointer or animation frame
Fix: Hold high-frequency state in a variable and flush it to the attribute when the interaction settles.
Storing secrets in the markup
Fix: Everything in the DOM is readable by any script on the page; keep credentials in memory or in a protected cookie.
Key Takeaways
- Data attributes keep state on the element it describes, so it survives re-renders, clones, and HTML round trips.
- Every dataset value is a string, which makes presence checks and numeric parsing explicit rather than implicit.
- Attribute names stay lowercase with dashes; the dataset property performs the camelCase translation.
- Delegated handlers read identifiers from attributes, so one listener covers rows that do not exist yet.
- Do not mirror values that already exist elsewhere, and never put credentials in the document.