HTML, CSS & JS, lesson 8
Time to put the pieces together. A to-do list uses everything from this course: a form to collect text, JavaScript to create elements, events to react, and CSS to show state.
So far you changed elements that already existed. You can also make new ones:
createElement builds an element that isn't on the page yet; append puts it inside another.
Trimming and ignoring empty input are small details that make an app feel solid.
You can keep state in CSS classes. Toggle a done class on click, and let CSS draw it:
To count unfinished tasks, select the items that don't have the class:
document.querySelectorAll("#list li:not(.done)").length.
One exercise to try what you just read.
Document.createElement()Make the to-do list work:
#todo-form adds an <li> with the (trimmed) input text to #list, then clears
#todo-input. Empty or whitespace-only input adds nothing.done on it.#remaining always shows how many items do not have the class done.const li = document.createElement("li");
li.textContent = "Buy flour";
document.querySelector("#list").append(li);const form = document.querySelector("#todo-form");
const input = document.querySelector("#todo-input");
form.addEventListener("submit", (event) => {
event.preventDefault(); // stay on this page
const text = input.value.trim();
if (!text) return; // ignore empty tasks
// …create the list item…
input.value = ""; // ready for the next one
});.done {
text-decoration: line-through;
opacity: 0.6;
}