Start learning free

LESSON 29 OF 161 · FRONTEND: JAVASCRIPT IN THE BROWSER

Find Many Elements

Practice

document.querySelector stops at the first element that matches. document.querySelectorAll gives back every match, in page order, as a list called a NodeList. Like an array, it has a length, works with for…of, and has positions: [0] is the first element.

An element also has its own querySelector, which searches only inside that element. A selector that starts with # picks an element by its id. Here is the idea on the page's links:

const links = document.querySelectorAll("a");
console.log(links.length + " links");
for (const link of links) {
  console.log(link.textContent);
}

This logs 3 links, then Details three times: one line per link, in page order. The number comes from the page, so a new link would be counted with no change to the script.

When the check opens the page, it must print:

> open the page
  console.log: app.js is running
  console.log: Mug
  console.log: Notebook
  console.log: Lamp
  screen:
    …
      heading 2: Our products
      text: 3 products
      list
        item
          heading 3: Mug (new)
        …
          heading 3: Notebook
        …
          heading 3: Lamp
        …

Your task: below the heading lines already in app.js, find all the product cards, write their number followed by " products" into the paragraph #count, log each card's h3 text in a loop, and add " (new)" to the heading of the first card.


Assignment
Follow the Coding Tutorial to find every card with querySelectorAll, count them into #count, loop over them to log their names, and change the first card's heading.


Hint
Call querySelector on a card, not on document, to search only inside that card. cards.length is the number of cards and cards[0] is the first one.


STEP 1 OF 8
    Ctrl + Enter to check