JavaScript Basics · Lesson 13 of 13

Project: A To-Do List

Your final project is a small app that people really use: a to-do list. Type a task, press the button, and the task appears in the list.

You need one new skill: making a brand new element.

Creating elements

const item = document.createElement("li");   // make a new <li>
item.textContent = "Buy milk";               // put text in it
list.append(item);                           // add it to the end of the list

createElement builds the element in memory. It only shows up on the page once you append it to an element that is already there.

The plan

When the button is clicked:

  1. Read the text from the input.
  2. If the text is empty, stop. return; inside the function does that.
  3. Create an <li>, put the text in it and append it to the list.
  4. Clear the input by setting its value to an empty string "", ready for the next task.

.trim() removes spaces from both ends of a string, so field.value.trim() is empty when someone typed only spaces.

Going further

When the checks pass, the course is complete. If you want more practice, try adding to the app: remove a task when it is clicked (item.remove()), or show how many tasks there are.

This is how every interactive web page works, at any size: listen for an event, read some data, update the page.

Your Task

  1. When the Add button is clicked, read the text from the input with the id task.
  2. If the text is empty (or only spaces), do nothing.
  3. Otherwise create an <li> with that text and append it to the list with the id list.
  4. Then empty the input.
  • The script creates elements with createElement
  • Typing a task and clicking Add puts it in the list
  • The input is emptied afterwards
  • A second task is added under the first
  • Clicking Add with an empty box, or only spaces, adds nothing