Showing an Array
Real apps usually keep their data in an array, and the page shows what's in the array. It's the same idea as the counter: the number lived in a variable, and the page only showed it. Here, the items live in an array, and a function draws them on the page:
const fruits = ["Apple", "Pear"];
const fruitList = document.querySelector("#fruits");
function showFruits() {
fruitList.textContent = "";
for (const fruit of fruits) {
const item = document.createElement("li");
item.textContent = fruit;
fruitList.append(item);
}
}
showFruits();The function first clears the list: setting textContent to an empty text removes everything inside the element. Then the loop creates one li for each element of the array. Whenever the array changes, call the function again to draw the list anew:
fruits.push("Banana");
showFruits();Why clear the list first? Without it, each call would add all the items again, below the ones already there, and the page would show Apple, Pear, Apple, Pear, Banana.
And why the array, when you could append items straight to the page? Because then the data stays in your program, where you can work with it: count the items with .length, check for an item with .includes() or add up prices in a loop. The array can also hold objects; the text of each item is then made from their properties, for example `${product.name}: ${product.price}`.
Instructions
- 1
Write a function
showTasks()that clearstaskListand then, for each task in the arraytasks, creates anliwith the task's text and appends it totaskList. Call the function at the end of the script, so that the tasks appear when the page loads. - 2
When
addButtonis clicked, add the text fromtaskInputto the arraytaskswithpush(), and callshowTasks()to draw the list again. - 3
Two improvements for the handler: if
taskInputis empty (itsvalueis""), don't add anything. And after adding a task, empty the field withtaskInput.value = "";, so that the user can type the next one right away.