Build a Todo App in Vanilla JavaScript
Build a todo app in vanilla JavaScript with add, complete, edit, delete, filters and localStorage persistence, using event delegation and no framework.

A todo app is the classic first project because it exercises everything a small interface needs: state, rendering, events, forms and persistence. Frameworks make it look easy by hiding the moving parts, and building one without a framework shows you what they hide. This post builds a todo app in vanilla JavaScript from scratch: a list you can add to, complete, edit and delete, a filter for all, active and completed items, a counter and persistence in localStorage so the list survives a reload. The code uses current browser features only: ES modules, crypto.randomUUID(), event delegation, <template> and a single render function. By the end you will have about 150 lines in three files, a clear separation between data and display, and a structure you can reuse for any small interface. Background on the pieces is on MDN.
The plan
The app has one rule: the state is a plain array, and the screen is a function of that array. Every change updates the array and then calls render(), which rebuilds the list. This avoids the bugs that come from changing the page and the data separately and letting them disagree.
Each todo is an object with an id, a text and a done flag.
// { id: string, text: string, done: boolean }
export function createTodo(text) {
return { id: crypto.randomUUID(), text: text.trim(), done: false };
}
export function toggle(todos, id) {
return todos.map((todo) => (todo.id === id ? { ...todo, done: !todo.done } : todo));
}
export function remove(todos, id) {
return todos.filter((todo) => todo.id !== id);
}
export function edit(todos, id, text) {
return todos.map((todo) => (todo.id === id ? { ...todo, text: text.trim() } : todo));
}
export function visible(todos, filter) {
if (filter === "active") return todos.filter((todo) => !todo.done);
if (filter === "completed") return todos.filter((todo) => todo.done);
return todos;
}
let todos = [createTodo("Buy milk")];
todos = toggle(todos, todos[0].id);
console.log(todos[0].done, visible(todos, "active").length);true 0These functions are pure: each returns a new array and never changes the old one. That keeps them easy to reason about and to test, and the model file has no mention of the page at all.
The markup
The page needs a form, a list, a counter and the filter buttons. The list item is a <template> so the script clones structure instead of concatenating HTML strings.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Todos</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<main>
<h1>Todos</h1>
<form id="new-todo">
<label for="text">New todo</label>
<input id="text" name="text" autocomplete="off" required>
<button type="submit">Add</button>
</form>
<ul id="list"></ul>
<footer>
<span id="count" aria-live="polite"></span>
<div id="filters" role="group" aria-label="Filter">
<button type="button" data-filter="all" aria-pressed="true">All</button>
<button type="button" data-filter="active" aria-pressed="false">Active</button>
<button type="button" data-filter="completed" aria-pressed="false">Completed</button>
</div>
<button type="button" id="clear">Clear completed</button>
</footer>
</main>
<template id="item">
<li>
<input type="checkbox" class="done" aria-label="Done">
<span class="text"></span>
<button type="button" class="edit">Edit</button>
<button type="button" class="delete" aria-label="Delete">×</button>
</li>
</template>
<script type="module" src="app.js"></script>
</body>
</html>(a heading, a form, an empty list, a footer with a counter and three filter buttons)The input has a real <label>, the form uses required for free validation, the filter group is a labeled set of toggle buttons with aria-pressed, and the counter is a live region, so assistive technology hears the number change.
Persistence
Saving to localStorage is a few lines, wrapped in try and catch because storage can be unavailable or full.
const KEY = "todos-v1";
export function load() {
try {
const raw = localStorage.getItem(KEY);
const data = raw ? JSON.parse(raw) : [];
return Array.isArray(data) ? data : [];
} catch {
return [];
}
}
export function save(todos) {
try {
localStorage.setItem(KEY, JSON.stringify(todos));
} catch {
// storage unavailable: the list works for this page view only
}
}
save([{ id: "1", text: "Buy milk", done: false }]);
console.log(load());[ { id: '1', text: 'Buy milk', done: false } ]The key carries a version suffix, so a future change to the shape can migrate or ignore old data. Parsing is guarded, because a corrupted value would otherwise crash the app at startup.
The app: state and render
The main file holds the state and one render() function. It reads the state, picks the visible items, clones the template for each and writes the counter.
import { createTodo, toggle, remove, edit, visible } from "./model.js";
import { load, save } from "./storage.js";
let todos = load();
let filter = "all";
const list = document.querySelector("#list");
const template = document.querySelector("#item");
const count = document.querySelector("#count");
function render() {
list.replaceChildren();
for (const todo of visible(todos, filter)) {
const node = template.content.firstElementChild.cloneNode(true);
node.dataset.id = todo.id;
node.classList.toggle("completed", todo.done);
node.querySelector(".done").checked = todo.done;
node.querySelector(".text").textContent = todo.text;
list.append(node);
}
const left = todos.filter((todo) => !todo.done).length;
count.textContent = `${left} ${left === 1 ? "item" : "items"} left`;
document.querySelectorAll("#filters button").forEach((button) => {
button.setAttribute("aria-pressed", String(button.dataset.filter === filter));
});
}
function update(next) {
todos = next;
save(todos);
render();
}
render();
console.log(count.textContent);0 items leftThe first run prints 0 items left because the list is empty. Using textContent means a todo like <img src=x onerror=alert(1)> is shown as text and never executed, which is the main reason to avoid building rows with innerHTML. Rebuilding the whole list is fast enough for a todo list of any realistic size.
Adding, completing and deleting
Instead of attaching a listener to every row, attach one to the list and find out what was clicked. This is event delegation: it works for rows that do not exist yet, and it never needs rebinding after a render.
document.querySelector("#new-todo").addEventListener("submit", (event) => {
event.preventDefault();
const input = event.target.elements.text;
if (!input.value.trim()) return;
update([...todos, createTodo(input.value)]);
input.value = "";
input.focus();
});
list.addEventListener("change", (event) => {
if (!event.target.matches(".done")) return;
const id = event.target.closest("li").dataset.id;
update(toggle(todos, id));
});
list.addEventListener("click", (event) => {
const id = event.target.closest("li")?.dataset.id;
if (!id) return;
if (event.target.matches(".delete")) update(remove(todos, id));
if (event.target.matches(".edit")) startEdit(event.target.closest("li"), id);
});(submitting adds a row; ticking a box strikes it; the cross removes it)After adding, the input is cleared and focused again, so a keyboard user can enter several items in a row. The checkbox uses the change event rather than click, because it also fires when the box is toggled by keyboard.
Editing in place
Editing swaps the text for an input. Commit on Enter or blur, cancel on Escape. Because render() rebuilds the row, the edit function replaces the span for as long as the input exists.
function startEdit(li, id) {
const span = li.querySelector(".text");
const input = document.createElement("input");
input.value = span.textContent;
input.setAttribute("aria-label", "Edit todo");
span.replaceWith(input);
input.focus();
input.select();
let finished = false;
function finish(commit) {
if (finished) return;
finished = true;
const text = input.value.trim();
if (commit && text) update(edit(todos, id, text));
else render();
}
input.addEventListener("keydown", (event) => {
if (event.key === "Enter") finish(true);
if (event.key === "Escape") finish(false);
});
input.addEventListener("blur", () => finish(true));
}(Edit turns the text into a focused input; Enter saves, Escape cancels)The finished flag prevents a double commit: pressing Enter triggers a render that removes the input, and the removal fires blur, which would otherwise call finish a second time. Committing an empty text is treated as a cancel here, though some apps delete the item instead, which is a design choice.
Filters and clearing
The filter buttons set a variable and re-render. The clear button removes every completed item.
document.querySelector("#filters").addEventListener("click", (event) => {
const button = event.target.closest("button[data-filter]");
if (!button) return;
filter = button.dataset.filter;
render();
});
document.querySelector("#clear").addEventListener("click", () => {
update(todos.filter((todo) => !todo.done));
});(Active shows unfinished items; Completed shows finished ones; Clear completed removes them)Notice that changing the filter calls render() without save(), since the filter is view state and not data. If you want the filter to survive a reload, store it in the URL hash and read it on load, which also makes each view linkable.
Styling and testing
A few lines of CSS give completed items a strike-through and keep the layout tidy.
body { font: 16px system-ui, sans-serif; max-width: 32rem; margin: 2rem auto; padding: 0 1rem; }
ul { list-style: none; padding: 0; }
li { display: flex; gap: 0.5rem; align-items: center; padding: 0.4rem 0; border-bottom: 1px solid #ddd; }
li .text { flex: 1; }
li.completed .text { text-decoration: line-through; color: #777; }
footer { display: flex; gap: 1rem; align-items: center; flex-wrap: wrap; margin-top: 1rem; }
button[aria-pressed="true"] { font-weight: 700; }(completed items are struck through and grey; the selected filter is bold)Because the model functions are pure, they test without a browser. Call toggle, remove, edit and visible with sample arrays and compare the results. Then test the interface by hand: add an item, reload and confirm it is still there, complete it, filter, edit with the keyboard only and clear completed.
Where to take it next
The structure scales. When the list grows large, render only the visible rows or paginate. For drag-and-drop ordering, store an order field. For sync across tabs, listen for the storage event and call load() followed by render(). For a server, replace load and save with fetch calls and keep the model unchanged. Each of these is a change in one file, which is the payoff of keeping data, storage and rendering apart.
What this version leaves out
A small app is a good place to be honest about what a real one would add. Accessibility is partly done: labels, live regions and pressed states are present, but focus management after deleting an item is missing, because the focused delete button disappears with its row and focus falls back to the page. Moving focus to the next item, or to the list heading when it is empty, is the polish that keyboard users notice.
Identity is solved by crypto.randomUUID(), which needs a secure context, so it works on HTTPS and localhost but not on a plain HTTP page. If you must support that case, generate an id from a counter you also persist. Concurrency is ignored too: two tabs editing the same list will overwrite each other, which the storage event can fix by reloading the state when another tab saves. Undo is another common request, and the pure model makes it easy, since you can keep a stack of previous arrays and restore the last one. Each of these is a small step on top of the structure, not a rewrite, which is the main reason to separate the model, storage and rendering from the start.


