×

javascript · level 2 · unit 1 · lesson 4

  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

finds every match, ready for a loop.

The text you hand to querySelector is a . #title finds an id, .price finds a class, and a bare tag name like li finds that tag. querySelector stops at the first match.

querySelectorAll collects every match into a list, in page order. It is not quite an array, but .length counts it and for...of walks through it, so you can change each element in turn.

No matches? You get an empty list, not null, so the loop runs zero times.

<ul>
  <li class="price">2</li>
  <li class="price">5</li>
  <li class="price">3</li>
</ul>
const prices = document.querySelectorAll(".price");
console.log(prices.length);
for (const price of prices) {
  price.textContent = `£${price.textContent}.00`;
}

Press run it to bring the page to life.

console

nothing logged yet

Each turn of a for...of loop gets a fresh variable, so const works there too.