Academy · Beginner · 15 min

JavaScript and the page: build a to-do list

Create elements, handle clicks and toggle classes to build a working to-do list.

The DOM is the live tree of elements in the page. JavaScript can create, change and remove them.

const li = document.createElement("li"); li.textContent = "Buy milk"; li.addEventListener("click", () => li.classList.toggle("done")); document.getElementById("list").appendChild(li);

Steps in the example

  1. Read the text from the input box.
  2. Create a list item and set its text.
  3. Toggle a CSS class when it is clicked.
  4. Add it to the list.

Challenge

Save the list with localStorage so it is still there after a refresh. This is how the free Tasks & Planner on GM works.

Common mistakes and practice

  • Running the script before the element exists. Put the script at the end of the body or wait for DOMContentLoaded.
  • Putting user input into innerHTML. Use textContent so typed text can never run as code.
  • Adding the same event listener repeatedly inside a loop or handler, which makes actions fire more than once.

Practice: Build a small to-do list: an input and an Add button that append items to a list, with a button on each item to remove it.

Common beginner mistakes with the DOM

When a script cannot find an element, the most common reasons are a typing mistake in the id, or running the script before the page has loaded. Put your script at the end of the body, or use the defer attribute, so the elements exist when the code runs.

The Console in your browser developer tools shows errors with the line number. Learning to read it is the fastest way to improve.

Practical tips

  • Use textContent instead of innerHTML when you insert plain text. It is safer.
  • Select with getElementById or querySelector and check the result is not null.
  • Add event listeners instead of writing onclick inside the HTML.
  • Press F12 in your browser to open the developer tools.