querySelector, querySelectorAll & textContent

Find elements on the page

Lesson 1 of 20 · 9 min · Module 1: The page is a tree

JavaScript in the browser works with the page through the DOM: a tree of objects, one for every element. Before you can change anything, you have to find the element you want.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Find one element with querySelector
  • Find many elements with querySelectorAll
  • Read and change text with textContent

The idea

document.querySelector(selector) returns the first element that matches a CSS selector, or null. document.querySelectorAll(selector) returns every match as a list with a length. textContent reads or replaces the text inside an element.

<h1 id="title">Welcome</h1>
<script>
  const title = document.querySelector('#title');
  title.textContent = 'Welcome back!';
  console.log(document.querySelectorAll('p').length);
</script>

01The DOM is the live page

When the browser reads your HTML, it builds a tree of objects. JavaScript changes that tree and the page updates at once. The Elements panel of the browser’s developer tools shows this live tree, not the original file.

02Selectors you already know

querySelector accepts any CSS selector: #id, .class, tag names, attributes, and combinations such as nav a.active. When nothing matches it returns null, so a typo in a selector usually shows up as an error the moment you use the result.

document.querySelector('#missing');             // null
document.querySelector('#missing').textContent; // error
Output
TypeError: Cannot read properties of null (reading 'textContent')

03A list, not an array

querySelectorAll returns a NodeList. It has length and forEach, but not map or filter. Spread it into an array when you need those: [...document.querySelectorAll('.lesson')].

Your turn

In the script: 1) change the text of #greeting to Hello, Ana!; 2) count the .lesson items and show the result in #count as 3 lessons, using the real number so it still works when lessons are added; 3) log the number with console.log.

What the checks look for

  • The greeting says Hello, Ana!
  • The count shows 3 lessons
  • The count adapts when a lesson is added
  • The number is logged
Try it in the editor →

Take this with you

Find elements with selectors, then change them through the DOM.

Go a little further

Use querySelectorAll and forEach to number every lesson: 1. Find elements, 2. Change content, and so on.

Learn JavaScript in the Browser for free

20 short lessons with real code and instant checks.

See the whole course →