javascript · level 2 · unit 3 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Loop over an array and append one element for each item.
Pages usually start from data. A shop has an array of products and a to-do app an array of jobs. Loop over the array with for...of, and for each item create an element, fill it in and append it.
The list is the , and every <li> you append becomes one of its children. Each is one item. Four items in the array make four children, and forty would make forty, with no extra code.
Change the array, run again, and the page follows.
<h2>Planets near the Sun</h2>
<ul id="planets"></ul> const list = document.querySelector("#planets");
const planets = ["Mercury", "Venus", "Earth", "Mars"];
for (const planet of planets) {
const item = document.createElement("li");
item.textContent = planet;
list.append(item);
} Press run it to bring the page to life.
console
nothing logged yet
Make the new element inside the loop, so every turn gets its own.
guess first
How many children does the queue get?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<ol id="queue"></ol> const queue = document.querySelector("#queue");
const people = ["Ava", "Ben", "Cleo"];
people.push("Dev");
for (const person of people) {
const spot = document.createElement("li");
spot.textContent = `${person} is waiting`;
queue.append(spot);
}
your turn
Your turn. Pack your beach bag.
Put three or more things to pack in the array, each in quotes. Then type the loop variable that holds each thing in the last blank. Press run.
the page your code works on
<h2>Pack for the beach</h2>
<ul id="bag"></ul>your javascript
Press run it to bring the page to life.
console
nothing logged yet
- the bag holds at least three thingsnot checked yet
- each thing shows its own namenot checked yet
fix it
Only one dog shows, and it is the last. Fix it!
the page your code works on
<h2>Dogs at the park</h2>
<ul id="dogs"></ul>your javascript
Press run it to bring the page to life.
console
nothing logged yet
- all three dogs are in the listnot checked yet
- the first dog is Biscuitnot checked yet
- Only one
<li>is ever made. Find the line that makes it. - Appending the same element again moves it to the end. Each dog needs a fresh element, made inside the loop.
- Move line 3 inside the loop, above item.textContent = dog;, then press run.
nailed it
you turned data into a page. :D
- Loop over an array and append one element per item.
- The list is the parent, and each item is a child.
- Create the element inside the loop, so each item gets its own.
new words in your collection
- parent
- child
This lesson isn’t saved. A free account remembers every lesson you finish.