Building Elements from Data

Writing every item into the HTML by hand stops working the moment the items come from data. Instead, build them: document.createElement("li") makes a new element, you set its text, and list.append(item) puts it on the page. A loop over an array then draws one element per item.

EXAMPLE · WEB PAGE
loading editor…
WHAT THIS DOES

The loop made one li element per city, set its text, and appended it to the list. Add a city to the array and the page gets another item; the HTML never changes.

YOUR TURN · WEB PAGE
Your turn → Change the data to an array of books, each an object with a title and a year, and show each one as Title (year) in its own li.
loading editor…

Syntax has to be exact. Every quote, bracket, brace and parenthesis needs its partner, and every HTML tag you open needs closing. One slip and the script won't run; the message under the page will say where.

querySelectorAll(selector) returns every match, not just the first, as a list you can loop over with for...of or forEach. Use it to change a whole group at once, such as every tab or every preset button.

EXAMPLE · WEB PAGE
loading editor…
WHAT THIS DOES

querySelectorAll returned all three buttons. forEach visited each one along with its position, and only the second one, at position 1, was given the on class.

◈ Graded Build

Draw one li inside #list for each name in the array, in order. Then write the number of names into #count, followed by the word names, such as 4 names. Count them with code, not by hand.

Checked by using your page: clicking, typing and waiting, then reading what changed. 3 visible and 1 hidden checks.

loading editor…

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Practice Test →
← Back