What you'll be able to do
By the end of this page you should be able to put data- attributes in HTML, read them with element.dataset, and wire delegation without id="row-482913" sprawl.
Previous post: DOMContentLoaded, defer, async.
Who this is for
- People hardcoding ids per list row
- Beginners using delegation who need “which id was clicked?”
- Anyone passing small config from HTML to JS
You can skip this if data-* is already your habit. Come back when selectors feel fragile.
HTML data-* and dataset
<button data-action="delete" data-id="42">Delete</button>
const btn = document.querySelector("button");
console.log(btn.dataset.action); // "delete"
console.log(btn.dataset.id); // "42"
Naming rule: data-user-id → dataset.userId (camelCase in JS).
Scenario A — delegation hub reads action + id.
Scenario B — toggle tabs data-tab="settings".
Delegation with dataset
list.addEventListener("click", function (event) {
const btn = event.target.closest("[data-action]");
if (!btn) return;
const action = btn.dataset.action;
const id = btn.dataset.id;
console.log(action, id);
});
Scenario A — one handler, many rows.
Scenario B — HTML stays declarative — designers see actions in markup.
Limits
- Values are strings. Coerce:
Number(btn.dataset.id). - Not for huge JSON blobs — use script type application/json or fetch later.
- Still validate on the server for real apps.
A tiny practice file
Save as data-attr.html.
<!DOCTYPE html>
<html>
<body>
<ul id="list">
<li><button data-action="pick" data-id="1">One</button></li>
<li><button data-action="pick" data-id="2">Two</button></li>
</ul>
<pre id="out"></pre>
<script>
document.getElementById("list").addEventListener("click", function (e) {
const btn = e.target.closest("[data-action]");
if (!btn) return;
document.getElementById("out").textContent =
btn.dataset.action + " id=" + btn.dataset.id;
});
</script>
</body>
</html>
Mistakes I see a lot
1. Expecting numbers without Number().
2. Typos: dataAction vs data-action.
3. Storing secrets in data attributes — visible in DOM.
4. Huge payloads in attributes — wrong tool.
What to try before the next post
- Read
datasetfrom two buttons. - Delegate
data-actionon a list. - Build
data-attr.html.
Next in this series: localStorage, sessionStorage, and cookies (concept).
Try this next outside the series
Browser JavaScript stops feeling isolated once you connect it to forms and component-oriented UI work.
- React forms without pain — see modern form handling after you understand the DOM version first
- HTML to JSX Converter — move tiny HTML snippets into React-style markup when you're ready