Sikau

JavaScript · Day 43 · about 25 min

Finding elements

The page as a family tree.

JavaScript meets the page

When a browser reads HTML, it builds a DOM — a family tree of objects, one per element. JavaScript can find any element in that tree and then read or change it. First step: finding.

querySelector

document.querySelector("selector") finds the first element matching a CSS selector — the same selectors you used in CSS.

const title = document.querySelector("#title");
console.log(title.textContent);

const firstDish = document.querySelector(".dish");
console.log(firstDish.textContent);

A family tree: The html element is the great-grandparent; body is a child; your h1 and p are grandchildren. querySelector is like asking "find me the first cousin called Thukpa".

The rest of this lesson

  • querySelectorAllexplain
  • Finding elements wellexplain
  • Predict the outputpredict
  • What does it find?predict
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 68 lessons of JavaScript