IntermediateLesson 11 of 307 min read

The DOM: selecting elements with querySelector

Understand the DOM as a tree and find any element with getElementById, querySelector and querySelectorAll.

In this lesson you will

  • Explain what the DOM is
  • Select one or many elements with CSS selectors
  • Move through parents, children and siblings
  • Avoid the script-runs-too-early bug

About 17 minutes

The page is a tree you can touch

When a browser loads your HTML, it does not keep it as plain text. It builds a living model of the page in memory, where every heading, paragraph and button is an object you can find, read and change. That model is called the DOM, the Document Object Model. Think of it as a family tree: the page is the great-grandparent, body is a child, a div inside it is a grandchild, and so on. JavaScript’s job is to walk that tree and change it.

Everything that makes a modern site feel alive, from menus that open to counters that tick, is just JavaScript finding an element in the DOM and changing something about it. This lesson teaches the first half of that sentence: finding things.

The document object

console.log(document.title);        // the page title
console.log(document.URL);          // the address
console.log(document.body);         // the body element
console.log(document.documentElement); // the html element

document is a built-in object that represents the whole page. Every search for an element starts from it.

Selecting one element

const title = document.getElementById("title");
const first = document.querySelector(".card");       // first match
const link  = document.querySelector("nav a[href]");  // any CSS selector

getElementById finds the element with that exact id. querySelector is more flexible: it accepts any CSS selector you already know from the CSS course, and returns the first match, or null if nothing matches. If you can style it with CSS, you can select it with querySelector.

Selecting many elements

const cards = document.querySelectorAll(".card");   // all matches
console.log(cards.length);

cards.forEach(card => {
  console.log(card.textContent);
});

for (const card of cards) { /* also works */ }

querySelectorAll returns a NodeList, a list-like collection. You can loop it with forEach or for...of and read its length. To use map or filter, convert it first with Array.from(cards).

Select every list item and print how many there are inside the result box. Then print the text of the second item.

<ul id="menu"><li>Home</li><li>Courses</li><li>Tools</li><li>Blog</li></ul>
<p id="out"></p>
<script>
  // select the li elements and write results into #out
</script>

const items = document.querySelectorAll(‘#menu li’); then write items.length and items[1].textContent into out.textContent

<ul id="menu"><li>Home</li><li>Courses</li><li>Tools</li><li>Blog</li></ul>
<p id="out"></p>
<script>
  const items = document.querySelectorAll('#menu li');
  const out = document.getElementById('out');
  out.textContent = items.length + ' items. Second: ' + items[1].textContent;
</script>

Selecting inside an element

const box = document.querySelector("#box");
const btn = box.querySelector("button");     // search only inside box
const all = box.querySelectorAll("p");

Any element has its own querySelector. Searching inside a smaller area is faster and avoids accidentally grabbing something with the same class elsewhere on the page.

Moving around the tree

Property Gives you
el.parentElement The element that contains it
el.children Its child elements
el.firstElementChild The first child
el.lastElementChild The last child
el.nextElementSibling The next element at the same level
el.previousElementSibling The previous one
el.closest(selector) The nearest ancestor (or itself) that matches

Start from the item with id ‘b’. Show its parent’s tag name, the text of its next sibling, and the text of its previous sibling.

<ul><li>One</li><li id="b">Two</li><li>Three</li></ul>
<pre id="out"></pre>
<script>
  const b = document.getElementById('b');
  // write the three answers into #out
</script>

Use b.parentElement.tagName, b.nextElementSibling.textContent and b.previousElementSibling.textContent

<ul><li>One</li><li id="b">Two</li><li>Three</li></ul>
<pre id="out"></pre>
<script>
  const b = document.getElementById('b');
  document.getElementById('out').textContent =
    'Parent: ' + b.parentElement.tagName + '\n' +
    'Next: ' + b.nextElementSibling.textContent + '\n' +
    'Previous: ' + b.previousElementSibling.textContent;
</script>

Reading what an element holds

const p = document.querySelector("p");
console.log(p.textContent);   // text only
console.log(p.innerHTML);     // text plus any tags inside
console.log(p.id, p.className);
console.log(p.getAttribute("data-level"));

Older methods you will still meet

Many tutorials and older sites use getElementsByClassName and getElementsByTagName. They work, but querySelector and querySelectorAll handle all of those cases with one consistent syntax. Prefer the modern pair.

Common mistake

Running your script before the element exists. If a script in the head runs before the body is built, querySelector returns null and the next line crashes with “Cannot read properties of null”. Fix it by using <script defer>, placing the script at the end of the body, or waiting for the DOMContentLoaded event.

document.addEventListener("DOMContentLoaded", () => {
  const title = document.querySelector("h1");
  console.log(title.textContent);
});

Checking that you found something

const banner = document.querySelector(".banner");

if (banner) {
  console.log("Found it");
} else {
  console.log("No banner on this page");
}

// or safely, with optional chaining
console.log(document.querySelector(".banner")?.textContent);
Practise in the live console

Open any website, press F12, open the Console and type document.querySelectorAll("a"). Look at its length to count every link on the page. Experimenting on real sites is the fastest way to learn selectors.

Worked example: highlight every external link

Here is a small but genuinely useful script. Many sites mark links that lead to other websites with a small arrow, so visitors know they are leaving. Selecting all the links, checking each address, and adding a class is a perfect first DOM job.

const links = document.querySelectorAll("a[href^='http']");

links.forEach(link => {
  if (!link.href.includes(location.hostname)) {
    link.classList.add("external");
    link.setAttribute("rel", "noopener");
  }
});
console.log(links.length + " links checked");

The selector a[href^='http'] means: links whose address starts with http. Attribute selectors like this one are very handy, and they are the same ones you learned in the CSS course. The test then compares each address with the current site name.

Count the links and mark every one that points to example.com by adding the class ‘ext’ (it turns pink). Show the count in the result.

<style>a.ext{color:#D63384;font-weight:700} body{font-family:Arial;padding:14px}</style>
<a href="https://example.com/a">Example A</a><br>
<a href="https://other.org/b">Other B</a><br>
<a href="https://example.com/c">Example C</a>
<p id="out"></p>
<script>
  // mark the example.com links and show how many
</script>

document.querySelectorAll(‘a’).forEach(a => { if (a.href.includes(‘example.com’)) a.classList.add(‘ext’); });

<style>a.ext{color:#D63384;font-weight:700} body{font-family:Arial;padding:14px}</style>
<a href="https://example.com/a">Example A</a><br>
<a href="https://other.org/b">Other B</a><br>
<a href="https://example.com/c">Example C</a>
<p id="out"></p>
<script>
  let n = 0;
  document.querySelectorAll('a').forEach(function (a) {
    if (a.href.includes('example.com')) { a.classList.add('ext'); n++; }
  });
  document.getElementById('out').textContent = n + ' of ' + document.querySelectorAll('a').length + ' links are example.com';
</script>

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What is the DOM?

  1. A CSS file
  2. A live model of the page that JavaScript can read and change
  3. A database
  4. A browser extension

The browser builds it from your HTML.

What does querySelector(".card") return?

  1. All cards
  2. A number
  3. Always an array
  4. The first matching element or null

It returns the first match, or null.

Which returns all matching elements?

  1. querySelectorAll
  2. querySelector
  3. getElement
  4. find

querySelectorAll returns a NodeList.

Why might querySelector return null?

  1. JavaScript is off
  2. Always on mobile
  3. The element does not exist yet or the selector is wrong
  4. It never does

Script ran too early or the selector did not match.

What does el.closest(".box") do?

  1. Closes the element
  2. Finds a child
  3. Deletes .box
  4. Finds the nearest ancestor matching .box

closest walks up the tree.

Summary

  • The DOM is a tree model of your page.
  • querySelector finds the first match, querySelectorAll finds all.
  • Navigate with parentElement, children and siblings.
  • Make sure the page is ready before selecting.

Next lesson

Next: changing text, attributes and styles on the elements you found.

Questions

What is the difference between a NodeList and an array?

A NodeList is list-like and can be looped, but lacks map and filter. Convert with Array.from.

Should I still use getElementById?

Yes, it is fast and clear for single elements with ids. querySelector is great for everything else.

Can I select elements by text?

Not directly. Select a group, then filter with JavaScript by comparing textContent.

Progress is saved in this browser.