×

javascript · level 2 · unit 3 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.