JSON & the DOM

Lesson 3 of 6

Selecting and Reading the DOM

Before you can change a page with JavaScript, you need to find the elements you want to change. document.querySelector and document.querySelectorAll use the same selector syntax as CSS.

const heading = document.querySelector('h1');
console.log(heading.textContent);

const allCards = document.querySelectorAll('.card');
console.log(allCards.length);

allCards.forEach(function (card) {
  console.log(card.getAttribute('data-id'));
});

This needs a real web page to query, so this block is read-only here, you'll get hands-on DOM practice in the final project.

Reading it

  • querySelector(selector) returns the first matching element, or null if nothing matches.
  • querySelectorAll(selector) returns a static list (a NodeList) of every matching element, it has .forEach, but isn't a real array.
  • .textContent reads (or sets) an element's text, ignoring any HTML tags inside it.
  • .getAttribute(name) reads an HTML attribute's raw string value, e.g. data-id, href, src.

📝 DOM Selection Quiz

Passing score: 70%
  1. 1.What does document.querySelector('.card') return if no element matches?

  2. 2.querySelectorAll returns a real Array with methods like map and filter.

  3. 3.element.____ reads or sets an element's visible text, ignoring HTML tags inside it.