Selecting elements

Topic 1 of 5 in Working with the DOM5 min readBeginnerFree course

Overview

When the browser loads a page, it builds the DOM (Document Object Model) — a tree of objects, one for every element. JavaScript can read and change that tree, and the page updates straight away.

On the left, an HTML file with a body containing an h1, a nav with two links, and a paragraph. On the right, the same structure as a tree: document, then body, then h1, nav and p.note, with two a elements under nav. querySelector(‘h1’) finds the h1; querySelectorAll(‘nav a’) finds both links.

Every element is a node in the tree. Elements have a parent, may have children, and sit next to siblings. The whole tree starts at the document object, which is your entry point for everything on the page.

The DOM is live: it isn’t the HTML file. If JavaScript adds an element, the DOM changes and the page shows it, even though the original file is untouched. DevTools’ Elements panel shows the current DOM.

Finding elements

document.querySelector takes any CSS selector and returns the first matching element:

JavaScript
const title = document.querySelector('h1');
const firstButton = document.querySelector('.lesson button');
const search = document.querySelector('#search');

querySelectorAll returns every match, which you can loop over:

JavaScript
const links = document.querySelectorAll('nav a');
links.forEach((link) => console.log(link.href));

Selectors you’ll use most

If you know CSS, you already know these:

Selector Matches
'h1' every <h1>
'.card' elements with class="card"
'#search' the element with id="search"
'nav a' <a> anywhere inside a <nav>
'ul > li' <li> that are direct children of a <ul>
'.card.active' elements with both classes
'[data-topic]' elements with a data-topic attribute
'input[type="email"]' email inputs
'li:first-child' the first <li> in each list
'h2, h3' all <h2> and <h3> elements

What you get back

  • querySelector returns an element, or null if nothing matches.
  • querySelectorAll returns a NodeList — like an array, with length, indexes and forEach, but without map or filter. Convert it when you need those: [...document.querySelectorAll('li')].

The NodeList from querySelectorAll is a snapshot: elements added later aren’t included. Select again if the page has changed.

Searching inside an element

Every element has its own querySelector, which searches only inside it. This keeps code from accidentally matching elements elsewhere on the page:

JavaScript
const card = document.querySelector('.card');
const cardTitle = card.querySelector('h3');      // only inside this card
const buttons = card.querySelectorAll('button');

Moving around the tree

Once you have an element, you can step to its relatives:

JavaScript
const item = document.querySelector('li');
item.parentElement;          // the <ul>
item.children;               // its child elements
item.nextElementSibling;     // the next <li>
item.previousElementSibling; // the previous <li>
item.closest('.card');       // nearest ancestor (or itself) matching the selector

closest is especially useful with events — finding the card that contains the button someone clicked.

Older methods

You’ll also see these in existing code. They still work:

JavaScript
document.getElementById('search');        // like querySelector('#search')
document.getElementsByClassName('card');  // a live collection
document.getElementsByTagName('li');

querySelector and querySelectorAll can do everything they can, with one consistent syntax.

Changing what you found

JavaScript
title.textContent = 'Arrow functions';
title.classList.add('is-active');

The next topic covers changing elements in detail.

Got null? The element doesn’t exist yet. Make sure your script has defer, or runs after the HTML it’s looking for.

Other reasons for null: a typo in the selector, forgetting the . for a class or # for an id (querySelector('card') looks for a <card> tag), or the element being added later by other code. Check it in the console with document.querySelector('…') to see exactly what matches.

Exercise

Change the heading

Select the page’s h1 and change its text to “Hello, DOM!”. Then select every li inside #topics and log how many there are.

JavaScript
const heading = /* select the h1 */;

Summary

  • The DOM is the browser’s live model of the page, as a tree of objects.
  • querySelector returns the first match (or null); querySelectorAll returns all of them.
  • Any CSS selector works — tags, classes, ids, attributes and combinations.
  • closest searches upwards; calling querySelector on an element searches inside it.
  • Select after the HTML exists — use defer or modules.