DOM & Events: Build a todo app

This tutorial walks through building a minimal todo app with vanilla JavaScript. You'll practice creating DOM elements, wiring event listeners, and saving state to localStorage.

HTML skeleton

<form id="todo-form">
  <input id="todo-input" placeholder="Add a task">
  <button>Add</button>
</form>
<ul id="todo-list"></ul>

Key JS snippets

const form = document.getElementById('todo-form');
const input = document.getElementById('todo-input');
const list = document.getElementById('todo-list');

form.addEventListener('submit', e => {
  e.preventDefault();
  const text = input.value.trim();
  if(!text) return;
  addTodo(text);
  input.value = '';
});

function addTodo(text){
  const li = document.createElement('li');
  li.textContent = text;
  const btn = document.createElement('button');
  btn.textContent = 'Done';
  btn.addEventListener('click', ()=> li.remove());
  li.appendChild(btn);
  list.appendChild(li);
}

Persistence with localStorage

Serialize todos as JSON and save them under a key:

function save(){
  const items = Array.from(list.children).map(li => li.firstChild.textContent);
  localStorage.setItem('todos', JSON.stringify(items));
}

Load saved items on startup and render them.

Polish & accessibility

Add ARIA roles for lists and ensure buttons have accessible names. Keep focus management in mind — focus the input after adding an item for a smooth keyboard experience.