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:
- Read the text from the input.
- If the text is empty, stop.
return;inside the function does that. - Create an
<li>, put the text in it and append it to the list. - Clear the input by setting its
valueto 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
- When the Add button is clicked, read the text from the input with the id
task. - If the text is empty (or only spaces), do nothing.
- Otherwise create an
<li>with that text and append it to the list with the idlist. - 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