Selecting elements
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.
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:
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:
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
querySelectorreturns an element, ornullif nothing matches.querySelectorAllreturns a NodeList — like an array, withlength, indexes andforEach, but withoutmaporfilter. 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:
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:
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 selectorclosest 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:
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
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 hasdefer, 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.
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.
const heading = /* select the h1 */;const heading = document.querySelector('h1');
heading.textContent = 'Hello, DOM!';
const items = document.querySelectorAll('#topics li');
console.log(items.length);Summary
- The DOM is the browser’s live model of the page, as a tree of objects.
querySelectorreturns the first match (ornull);querySelectorAllreturns all of them.- Any CSS selector works — tags, classes, ids, attributes and combinations.
closestsearches upwards; callingquerySelectoron an element searches inside it.- Select after the HTML exists — use
deferor modules.