javascript · level 2 · unit 1 · lesson 4
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Which paragraphs change? Guess.
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<p class="pet">Rex</p>
<p class="pet">Tibbles</p>
<p>Not a pet</p>
<p class="pet">Nibbles</p> const pets = document.querySelectorAll(".pet");
for (const pet of pets) {
pet.textContent = pet.textContent.toUpperCase();
}
console.log(pets.length);
your turn
Your turn. Put everything on sale.
Fill in a selector that finds all three items, then the class that marks them as on sale. Press run and every item turns bold and red.
the page your code works on
<style>
.sale { color: crimson; font-weight: bold; }
</style>
<ul>
<li class="item">Scarf</li>
<li class="item">Gloves</li>
<li class="item">Hat</li>
</ul>your javascript
Press run it to bring the page to life.
console
nothing logged yet
- all three items are on salenot checked yet
- the hat is half price toonot checked yet
fix it
No star lights up, and there is no error. Fix it!
the page your code works on
<style>
.lit { color: gold; }
</style>
<p class="star">★</p>
<p class="star">★</p>
<p class="star">★</p>your javascript
Press run it to bring the page to life.
console
nothing logged yet
- all three stars light upnot checked yet
- The console says 0 stars lit, so
querySelectorAllfound nothing to loop over. - The stars wear the class star. A selector for a class needs something in front of the name.
- Change "star" to ".star" on line 1, then press run.
nailed it
you changed the whole page in one go. :D
#finds an id,.finds a class, a bare name finds a tag.querySelectorAllhands back every match, ready forfor...of.- No matches gives an empty list, so the loop never runs.
new words in your collection
- selector
- querySelectorAll
This lesson isn’t saved. A free account remembers every lesson you finish.