JavaScript - 22

JavaScript - 22: To-Do List (Add Items)

In this lesson, you will create new list items with JavaScript and add them to a simple to-do list.

Your challenge: Read the task from the input, create a new <li>, add it to the list, and clear the input afterward.

✦ JavaScript Editor
▶ Live Output

Create a new element

JavaScript can create HTML elements with: document.createElement()

For this project: const li = document.createElement("li"); creates a new list item.

Add the task text

Read the input with: taskInput.value

Then place that text inside the new list item: li.textContent = taskInput.value;

Add the item to the list

Use: todoList.appendChild(li);

This places the new <li> inside the existing <ul>.

Stop empty tasks

Before creating the item, check: taskInput.value.trim() === ""

If it is empty, use return so nothing is added.

Clear the input

After adding the task: taskInput.value = "";

Now the input is ready for another task.

Try it: Add several different tasks and watch JavaScript create a new list item each time.

Small experiment: Add taskInput.focus(); after clearing the input so the cursor returns there automatically.

Good JavaScript habit: Use .trim() before checking user-entered text so spaces by themselves do not count as a real task.

👀 Show Solution
const taskInput = document.getElementById("taskInput");
const addBtn = document.getElementById("addBtn");
const todoList = document.getElementById("todoList");

addBtn.addEventListener("click", function() {
  if (taskInput.value.trim() === "") {
    return;
  }

  const li = document.createElement("li");
  li.textContent = taskInput.value.trim();

  todoList.appendChild(li);

  taskInput.value = "";
  taskInput.focus();
});

The button click creates a new <li>, fills it with the entered task, and adds it to the unordered list.