Build a to-do list: plain JavaScript, then XON
Handle many buttons with one listener, keep state in one object and draw the page from it without innerHTML; then write the same list with a store and a keyed row.
What you will be able to do
- Handle every row's buttons with one delegated listener
- Keep the state in one object and draw the list from it with render()
- Build rows with a template and textContent, never with innerHTML
- Filter while typing with includes(), and say why no pattern is built from the text
- Write the same list in XON and explain what a key changes
One listener, many targets
A to-do list has many buttons, and the number changes as the person adds and removes tasks. Do not attach a listener to each button. Attach one listener to the list. A click on a button inside the list bubbles up to the list, where the listener can ask which button was clicked.
This is called event delegation. In the handler, event.target.closest('button[data-action]') finds the button the click started in, or the nearest button around it. If the click was not on a button, the result is null and the handler returns. Rows that are added later need no new listener.
A state object and a render function
Keep everything the page knows in one object: the tasks, the next id and the filter text. Write one function, render(), that draws the list from that object. Every change follows the same steps: change the object, call render(), and then look after focus, which the next paragraphs explain.
This avoids the bug where the page and the data disagree. The list is never edited by hand. It is always drawn again from the state, so a task that is in the data is on the page and a task that is not in the data is not.
Drawing again has a cost. render() deletes the old buttons and makes new ones, and a deleted button cannot keep focus. The browser moves focus to the page, and a person using the keyboard or a screen reader has to start again from the top after every action. So render() must note which button had focus and focus its new copy. A removed task has no new copy, so the click handler moves focus to the row that took its place, or to the new-task field when the list is empty.
var state = { nextId: 4, filter: '', items: [ /* { id, text, done } */ ] };
list.addEventListener('click', function (event) {
var button = event.target.closest('button[data-action]');
if (!button) return;
var row = button.closest('li');
var action = button.dataset.action;
var place = Array.prototype.indexOf.call(list.children, row);
/* change state.items here */
render(); /* the old buttons are gone */
if (action === 'remove') { /* nothing to give back: use a neighbour */
var rows = list.children;
var next = rows[Math.min(place, rows.length - 1)];
(next ? next.querySelector('button[data-action="toggle"]') : input).focus();
} else { /* put focus on the new copy of the same button */
list.querySelector('li[data-id="' + row.dataset.id + '"] button[data-action="' + action + '"]').focus();
}
});
render().Nodes with textContent and a template
Each row is made from a template element. The browser does not display a template, but it keeps its content as a fragment that you can copy. Clone the first element of the fragment, fill it, and append it to the list. The row's markup lives in the HTML, where you can read it and style it in one place.
Fill the row with textContent. It sets text and never parses HTML, so a task named <b>bold</b> shows exactly those characters. The alternative, assigning a string to the property named innerHTML, parses the string as HTML. If the string came from a person, that is how script injection starts.
row.innerHTML = '<span>' + item.text + '</span>';
The first example's checks type a tag into the task field and confirm that no b element appears. They also press the buttons and confirm that focus is still on a button of the list afterwards.
HTML
<section class="todo-plain" aria-labelledby="todo-plain-title">
<h2 class="todo-plain__title" id="todo-plain-title">Tasks</h2>
<form class="todo-plain__add" id="todo-plain-form">
<label for="todo-plain-input">New task</label>
<input id="todo-plain-input" type="text" autocomplete="off">
<button class="todo-plain__button" id="todo-plain-add">Add</button>
</form>
<p class="todo-plain__filter">
<label for="todo-plain-filter">Filter tasks</label>
<input id="todo-plain-filter" type="search" autocomplete="off">
</p>
<p class="todo-plain__count" id="todo-plain-count" role="status"></p>
<ul class="todo-plain__list" id="todo-plain-list"></ul>
<p class="todo-plain__empty" id="todo-plain-empty" hidden>No task matches.</p>
<template id="todo-plain-row">
<li class="todo-plain__row">
<button type="button" class="todo-plain__toggle" data-action="toggle" aria-pressed="false">Task</button>
<button type="button" class="todo-plain__remove" data-action="remove">Remove</button>
</li>
</template>
</section>CSS
.todo-plain {
--tp-bg: #ffffff;
--tp-fg: #1b1f2a;
--tp-muted: #4a5163;
--tp-line: #6b7280;
--tp-accent: #3730a3;
--tp-on-accent: #ffffff;
--tp-mark: #ffe58a;
--tp-mark-text: #1b1f2a;
max-width: 32rem;
padding: 1rem;
color: var(--tp-fg);
background: var(--tp-bg);
}
.todo-plain__title { margin: 0 0 0.75rem; font-size: 1.25rem; }
.todo-plain__add { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 0.25rem 0.5rem; align-items: end; margin: 0 0 0.75rem; }
.todo-plain__add label { grid-column: 1 / -1; font-weight: 600; }
.todo-plain__filter { display: grid; gap: 0.25rem; margin: 0 0 0.5rem; }
.todo-plain__filter label { font-weight: 600; }
.todo-plain input {
min-width: 0;
min-height: 44px;
padding: 0.25rem 0.5rem;
font: inherit;
color: var(--tp-fg);
background: var(--tp-bg);
border: 1px solid var(--tp-line);
border-radius: 6px;
}
.todo-plain__button,
.todo-plain__remove {
min-height: 44px;
padding: 0.25rem 1rem;
font: inherit;
color: var(--tp-on-accent);
background: var(--tp-accent);
border: 1px solid var(--tp-accent);
border-radius: 6px;
cursor: pointer;
}
.todo-plain__remove { color: var(--tp-accent); background: transparent; }
.todo-plain__count { margin: 0 0 0.5rem; color: var(--tp-muted); }
.todo-plain__list { margin: 0; padding: 0; list-style: none; }
.todo-plain__row { display: flex; align-items: center; gap: 0.5rem; padding-block: 0.25rem; border-block-end: 1px solid var(--tp-line); }
.todo-plain__toggle {
flex: 1;
min-width: 0;
overflow-wrap: anywhere;
min-height: 44px;
padding: 0.25rem 0.5rem;
font: inherit;
text-align: start;
color: var(--tp-fg);
background: transparent;
border: 0;
cursor: pointer;
}
.todo-plain__toggle[aria-pressed="true"] { color: var(--tp-muted); text-decoration: line-through; }
.todo-plain__toggle mark { color: var(--tp-mark-text); background: var(--tp-mark); }
.todo-plain input:focus-visible,
.todo-plain__button:focus-visible,
.todo-plain__toggle:focus-visible,
.todo-plain__remove:focus-visible {
outline: 3px solid var(--tp-accent);
outline-offset: 2px;
}
@media (prefers-color-scheme: dark) {
.todo-plain {
--tp-bg: #12141c;
--tp-fg: #eceef5;
--tp-muted: #b6bccb;
--tp-line: #8b93a7;
--tp-accent: #b4b8ff;
--tp-on-accent: #12141c;
--tp-mark: #5c4b00;
--tp-mark-text: #fff3c4;
}
}JavaScript
// State lives in one object. render() draws the whole list from it; nothing else touches the list.
var state = {
nextId: 4,
filter: '',
items: [
{ id: 1, text: 'Water the plants', done: false },
{ id: 2, text: 'Write the report', done: true },
{ id: 3, text: 'Book the meeting room', done: false }
]
};
var form = document.getElementById('todo-plain-form');
var input = document.getElementById('todo-plain-input');
var filterInput = document.getElementById('todo-plain-filter');
var list = document.getElementById('todo-plain-list');
var empty = document.getElementById('todo-plain-empty');
var count = document.getElementById('todo-plain-count');
var template = document.getElementById('todo-plain-row');
// Show the text with the matching part wrapped in <mark>. Nodes are built one by one, no HTML is parsed.
function fillText(target, text, query) {
var at = query ? text.toLowerCase().indexOf(query) : -1;
if (at === -1) {
target.textContent = text;
return;
}
var mark = document.createElement('mark');
mark.textContent = text.slice(at, at + query.length);
target.textContent = '';
target.append(text.slice(0, at), mark, text.slice(at + query.length));
}
// Drawing the list again destroys the buttons, and a destroyed button cannot keep focus. Without this the focus falls back
// to the page, and a keyboard or screen-reader user has to start from the top after every action. So render() notes which
// row and which button had focus, and puts focus on the new copy of that same button.
function render() {
var held = list.contains(document.activeElement) ? document.activeElement.closest('button[data-action]') : null;
var heldId = held ? held.closest('li').dataset.id : null;
var heldAction = held ? held.dataset.action : null;
var query = state.filter.trim().toLowerCase();
var shown = state.items.filter(function (item) {
return item.text.toLowerCase().includes(query); // plain text comparison: no regular expression
});
list.textContent = '';
shown.forEach(function (item) {
var row = template.content.firstElementChild.cloneNode(true);
var toggle = row.querySelector('[data-action="toggle"]');
row.dataset.id = String(item.id);
toggle.setAttribute('aria-pressed', String(item.done));
fillText(toggle, item.text, query);
list.appendChild(row);
});
empty.hidden = shown.length > 0;
var left = state.items.filter(function (item) { return !item.done; }).length;
count.textContent = left + ' of ' + state.items.length + ' tasks left';
if (held) {
var again = list.querySelector('li[data-id="' + heldId + '"] button[data-action="' + heldAction + '"]');
if (again) again.focus();
}
}
// One listener on the list serves every row, including rows added later.
list.addEventListener('click', function (event) {
var button = event.target.closest('button[data-action]');
if (!button) return;
var id = Number(button.closest('li').dataset.id);
if (button.dataset.action === 'remove') {
// The removed row's button is gone, so there is nothing to give focus back to. Move it to the nearest row instead:
// the row that took its place, or the one before it, or the "New task" field when the list is empty.
var place = Array.prototype.indexOf.call(list.children, button.closest('li'));
state.items = state.items.filter(function (item) { return item.id !== id; });
render();
var rows = list.children;
var next = rows[Math.min(place, rows.length - 1)];
(next ? next.querySelector('[data-action="toggle"]') : input).focus();
return;
}
state.items.forEach(function (item) { if (item.id === id) item.done = !item.done; });
render();
});
form.addEventListener('submit', function (event) {
event.preventDefault();
var text = input.value.trim();
if (!text) return;
state.items.push({ id: state.nextId++, text: text, done: false });
input.value = '';
render();
});
filterInput.addEventListener('input', function () {
state.filter = filterInput.value;
render();
});
render();Filtering while typing
The filter field narrows the list as the person types. Lower-case both the task and the typed text, then test with includes(). The method is case-sensitive, so lower-casing is what makes "ROOM" find "room".
It is tempting to build a regular expression from the typed text with new RegExp(text). Do not. The characters a person types may be special in a pattern. A single ( makes the constructor throw an error, and .* matches everything. MDN's guide to regular expressions notes that string methods such as includes() need no escaping. The example's check types both of these and confirms that nothing matches and nothing breaks.
The highlight is built from nodes. The script finds where the match starts, then appends three pieces to the button: the text before, a mark element holding the matched text, and the text after. No HTML is parsed.
The same with XON
XON removes the listener and the drawing code. You describe the data with xon.data('todo', …), and you describe the row in the HTML. data-each="todo.rows" repeats the one element inside the list for each item. A blank such as {title} in the row is filled with the item's field as text. Buttons name your functions with data-on-click, and the script offers those functions with xon.use(). Markup can call only functions that were offered.
The fields use data-model, so what the person types is the data. The rest of the script has the same shape as before: change the data and let the page follow. Focus is the exception. A toggle keeps its button, because the keyed list keeps the row, so focus stays. A removed task takes its button with it, and a removed button cannot keep focus. The remove function therefore calls xon.flush(), so XON draws the list now, and then moves focus to the next row's toggle button, or to the new-task field when no row is left. This example keeps a second list, todo.rows, that holds the filtered items, and it rebuilds that list whenever the items or the filter change.
HTML
<section class="todo-xon" aria-labelledby="todo-xon-title">
<h2 class="todo-xon__title" id="todo-xon-title">Tasks</h2>
<form class="todo-xon__add" id="todo-xon-form" data-on-submit="addTask">
<label for="todo-xon-input">New task</label>
<input id="todo-xon-input" type="text" autocomplete="off" data-model="todo.draft">
<button class="todo-xon__button" id="todo-xon-add">Add</button>
</form>
<p class="todo-xon__filter">
<label for="todo-xon-filter">Filter tasks</label>
<input id="todo-xon-filter" type="search" autocomplete="off" data-model="todo.filter">
</p>
<p class="todo-xon__count" id="todo-xon-count" role="status" data-text="todo.left"></p>
<ul class="todo-xon__list" id="todo-xon-list" data-each="todo.rows" data-each-key="id">
<li class="todo-xon__row {cls}">
<span class="todo-xon__text">{title}</span>
<button type="button" class="todo-xon__toggle" data-on-click="toggleTask" data-id="{id}">{label}</button>
<button type="button" class="todo-xon__remove" data-on-click="removeTask" data-id="{id}">Remove</button>
</li>
</ul>
<p class="todo-xon__empty" id="todo-xon-empty" data-if="todo.empty">No task matches.</p>
</section>CSS
.todo-xon {
--tx-bg: #ffffff;
--tx-fg: #1b1f2a;
--tx-muted: #4a5163;
--tx-line: #6b7280;
--tx-accent: #3730a3;
--tx-on-accent: #ffffff;
max-width: 32rem;
padding: 1rem;
color: var(--tx-fg);
background: var(--tx-bg);
}
.todo-xon__title { margin: 0 0 0.75rem; font-size: 1.25rem; }
.todo-xon__add { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 0.25rem 0.5rem; align-items: end; margin: 0 0 0.75rem; }
.todo-xon__add label { grid-column: 1 / -1; font-weight: 600; }
.todo-xon__filter { display: grid; gap: 0.25rem; margin: 0 0 0.5rem; }
.todo-xon__filter label { font-weight: 600; }
.todo-xon input {
min-width: 0;
min-height: 44px;
padding: 0.25rem 0.5rem;
font: inherit;
color: var(--tx-fg);
background: var(--tx-bg);
border: 1px solid var(--tx-line);
border-radius: 6px;
}
.todo-xon__button,
.todo-xon__toggle,
.todo-xon__remove {
min-height: 44px;
padding: 0.25rem 1rem;
font: inherit;
color: var(--tx-on-accent);
background: var(--tx-accent);
border: 1px solid var(--tx-accent);
border-radius: 6px;
cursor: pointer;
}
.todo-xon__toggle,
.todo-xon__remove { color: var(--tx-accent); background: transparent; }
.todo-xon__count { margin: 0 0 0.5rem; color: var(--tx-muted); }
.todo-xon__list { margin: 0; padding: 0; list-style: none; }
.todo-xon__row { display: flex; flex-wrap: wrap; align-items: center; gap: 0.5rem; padding-block: 0.25rem; border-block-end: 1px solid var(--tx-line); }
.todo-xon__text { flex: 1 1 8rem; min-width: 0; overflow-wrap: anywhere; }
.todo-xon__row--done .todo-xon__text { color: var(--tx-muted); text-decoration: line-through; }
.todo-xon__empty { margin: 0.5rem 0 0; }
.todo-xon input:focus-visible,
.todo-xon__button:focus-visible,
.todo-xon__toggle:focus-visible,
.todo-xon__remove:focus-visible {
outline: 3px solid var(--tx-accent);
outline-offset: 2px;
}
@media (prefers-color-scheme: dark) {
.todo-xon {
--tx-bg: #12141c;
--tx-fg: #eceef5;
--tx-muted: #b6bccb;
--tx-line: #8b93a7;
--tx-accent: #b4b8ff;
--tx-on-accent: #12141c;
}
}JavaScript
var todo = xon.data('todo', {
draft: '',
filter: '',
next: 4,
left: '',
empty: false,
items: [
{ id: 1, title: 'Water the plants', done: false },
{ id: 2, title: 'Write the report', done: true },
{ id: 3, title: 'Book the meeting room', done: false }
],
rows: []
});
// The page shows todo.rows. This function rebuilds it from the items and the filter.
function refresh() {
var query = todo.filter.trim().toLowerCase();
todo.rows = todo.items
.filter(function (item) { return item.title.toLowerCase().includes(query); })
.map(function (item) {
return {
id: item.id,
title: item.title,
label: item.done ? 'Mark as not done' : 'Mark as done',
cls: item.done ? 'todo-xon__row--done' : ''
};
});
var left = todo.items.filter(function (item) { return !item.done; }).length;
todo.left = left + ' of ' + todo.items.length + ' tasks left';
todo.empty = todo.rows.length === 0;
}
function addTask(event) {
event.preventDefault();
var title = todo.draft.trim();
if (!title) return;
todo.items.push({ id: todo.next++, title: title, done: false });
todo.draft = '';
refresh();
}
function toggleTask(event, button) {
var id = Number(button.dataset.id);
todo.items.forEach(function (item) { if (item.id === id) item.done = !item.done; });
refresh();
}
// The Remove button that was pressed is deleted with its row, and a deleted button cannot keep focus: the browser drops it
// to the page. So note where the row was, let XON draw the list (xon.flush()), then focus the toggle button of the row that
// took its place, or of the last row, or the "New task" field when no row is left. Toggle needs none of this: the keyed
// list keeps the same button, so focus stays on it.
function removeTask(event, button) {
var id = Number(button.dataset.id);
var list = document.getElementById('todo-xon-list');
var place = Array.prototype.indexOf.call(list.children, button.closest('li'));
todo.items = todo.items.filter(function (item) { return item.id !== id; });
refresh();
xon.flush();
var rows = list.children;
var next = rows[Math.min(place, rows.length - 1)];
(next ? next.querySelector('.todo-xon__toggle') : document.getElementById('todo-xon-input')).focus();
}
xon.use(addTask, toggleTask, removeTask);
xon.watch('todo.filter', refresh);
refresh();What the key changes
A list in XON can have a key: data-each-key="id". The key names the field that identifies an item. With a key, XON can tell that a row belongs to an item, so when the list is reordered it moves the row. Without a key, XON matches rows to items by position, so each row is kept in its place and shows whichever item is now there.
That difference shows up in anything the page remembers outside your data, such as text typed into a field. In the last example, both lists hold the same four items. Type in the fields of the first two rows, then press the button. In the keyed list, the note stays with its item and moves with it to its new place. In the unkeyed list, the note stays at its position, beside a different item.
HTML
<section class="key-demo" aria-labelledby="key-demo-title">
<h2 class="key-demo__title" id="key-demo-title">Type a note, then reorder</h2>
<p>Type in a note field, then press the button. The first item moves to the end of both lists.</p>
<p><button type="button" class="key-demo__button" id="key-demo-rotate" data-on-click="rotate">Move the first item to the end</button></p>
<div class="key-demo__lists">
<section aria-labelledby="key-demo-keyed-title">
<h3 class="key-demo__subtitle" id="key-demo-keyed-title">With data-each-key</h3>
<ul class="key-demo__list" id="key-demo-keyed" data-each="keyed.items" data-each-key="id">
<li class="key-demo__row"><label>{name} <input type="text" autocomplete="off"></label></li>
</ul>
</section>
<section aria-labelledby="key-demo-unkeyed-title">
<h3 class="key-demo__subtitle" id="key-demo-unkeyed-title">Without a key</h3>
<ul class="key-demo__list" id="key-demo-unkeyed" data-each="unkeyed.items">
<li class="key-demo__row"><label>{name} <input type="text" autocomplete="off"></label></li>
</ul>
</section>
</div>
</section>CSS
.key-demo {
--kd-bg: #ffffff;
--kd-fg: #1b1f2a;
--kd-line: #6b7280;
--kd-accent: #3730a3;
--kd-on-accent: #ffffff;
padding: 1rem;
color: var(--kd-fg);
background: var(--kd-bg);
}
.key-demo__title { margin: 0 0 0.5rem; font-size: 1.25rem; }
.key-demo__subtitle { margin: 0 0 0.5rem; font-size: 1rem; }
.key-demo__lists { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 15rem), 1fr)); gap: 1rem; }
.key-demo__list { margin: 0; padding: 0; list-style: none; }
.key-demo__row { margin-block: 0.5rem; }
.key-demo__row label { display: grid; gap: 0.25rem; font-weight: 600; }
.key-demo__row input {
min-height: 44px;
padding: 0.25rem 0.5rem;
font: inherit;
font-weight: 400;
color: var(--kd-fg);
background: var(--kd-bg);
border: 1px solid var(--kd-line);
border-radius: 6px;
}
.key-demo__button {
min-height: 44px;
padding: 0.5rem 1rem;
font: inherit;
color: var(--kd-on-accent);
background: var(--kd-accent);
border: 1px solid var(--kd-accent);
border-radius: 8px;
cursor: pointer;
}
.key-demo__button:focus-visible,
.key-demo__row input:focus-visible {
outline: 3px solid var(--kd-accent);
outline-offset: 2px;
}
.key-demo__button:focus-visible { outline-color: var(--kd-fg); }
@media (prefers-color-scheme: dark) {
.key-demo {
--kd-bg: #12141c;
--kd-fg: #eceef5;
--kd-line: #8b93a7;
--kd-accent: #b4b8ff;
--kd-on-accent: #12141c;
}
}JavaScript
var names = ['Red', 'Green', 'Blue', 'Yellow'];
function makeItems() {
return names.map(function (name, index) { return { id: index + 1, name: name }; });
}
var keyed = xon.data('keyed', { items: makeItems() });
var unkeyed = xon.data('unkeyed', { items: makeItems() });
// Both lists get the same change: the first item goes to the end.
function rotate() {
keyed.items = keyed.items.slice(1).concat(keyed.items.slice(0, 1));
unkeyed.items = unkeyed.items.slice(1).concat(unkeyed.items.slice(0, 1));
}
xon.use(rotate);Open in the Playground: Keyed and unkeyed rows after a reorder
Use a key for any list a visitor works in. If you keep what the visitor types in your data, as the to-do example does, the rows follow their items either way.
All examples on this page passed their checks in Chrome 143 on 3 December 2026. They were not tested in other browsers.
References
- MDN: Event bubbling (read on 3 December 2026)
- MDN: the template element (read on 3 December 2026)
- MDN: Node.textContent (read on 3 December 2026)
- MDN: Element.innerHTML (read on 3 December 2026)
- MDN: String.prototype.includes() (read on 3 December 2026)
- MDN: Regular expressions (read on 3 December 2026)
- XON documentation: the guide, lists with data-each (read on 3 December 2026)
Snippets that go with this tutorial
These snippets in the gallery use the same techniques: