Code / JavaScript from Zero / Unit 5: The DOM and events

Build a to-do app टू-डू ऐप बनाइए

Lesson 12 of 15 · about 18 minutes · Read an input, create list items, and mark them done.

⚡ 0 XP

Step 1 of 2

Add tasks to a list

bodyh1ul"text"li

To build new parts of a page:

  • input.value is what the user typed (use .trim() to drop extra spaces)
  • document.createElement("li") makes a new, empty <li>
  • set its textContent, then list.appendChild(li) puts it on the page

Good apps also check for empty input and clear the box after adding (input.value = "";).

Example
const ul = document.querySelector("ul");
const li = document.createElement("li");
li.textContent = "Water the tulsi plant";
ul.appendChild(li);

🎯 Challenge: The Add button +20 XP

When Add is clicked:

  1. Read the text from #task (trimmed). If it is empty, do nothing.
  2. Create an <li> with that text and add it to #list.
  3. Clear the input box.

Try twice to unlock the solution (0/2)

script.jsCtrl ⏎
Preview
Console

Output from console.log appears here.

Checklist

Press Run to check your code.

  • Adding “Buy milk” puts it in the list
  • The input is cleared after adding
  • Empty or blank tasks are ignored
  • New tasks go at the end
Lesson notes (text version)

1. Add tasks to a list

To build new parts of a page:

  • input.value is what the user typed (use .trim() to drop extra spaces)
  • document.createElement("li") makes a new, empty <li>
  • set its textContent, then list.appendChild(li) puts it on the page

Good apps also check for empty input and clear the box after adding (input.value = "";).

                const ul = document.querySelector("ul");
const li = document.createElement("li");
li.textContent = "Water the tulsi plant";
ul.appendChild(li);
              

Challenge: The Add button

When Add is clicked:

  1. Read the text from #task (trimmed). If it is empty, do nothing.
  2. Create an <li> with that text and add it to #list.
  3. Clear the input box.

2. Mark tasks as done

Each new <li> can have its own click listener. classList.toggle("done") adds the class if it is missing and removes it if it is there — perfect for ticking a task on and off.

To count tasks still left, select only the items without the class: list.querySelectorAll("li:not(.done)").length. Update that count every time something changes.

                li.addEventListener("click", () => {
  li.classList.toggle("done");
  updateLeft();
});
              

Challenge: Tick off tasks

Adding tasks already works. Now:

  1. Complete updateLeft() so #left shows how many tasks are not done, like 2 left.
  2. Call updateLeft() after adding a task.
  3. Clicking a task toggles the class done on it, then updates the count.

Search by task, format or tool name.