Skip to content
jshacks.dev
Browser

Select elements with querySelector and querySelectorAll

Select the first match with querySelector, which returns null on a miss, or all matches with querySelectorAll, a static NodeList. All modern browsers.

1 min read
Summarize in AI

You need one element, or all of them, by CSS selector. The two methods differ in what they return and in what they do when nothing matches.

select.jsJavaScript
document.body.innerHTML = '<ul><li class="item">A</li><li class="item">B</li></ul>';

const first = document.querySelector('.item');
const all = document.querySelectorAll('.item');
const missing = document.querySelector('.nope');

document.querySelector('ul').append(document.createElement('li'));

console.log(first.textContent, all.length, missing);
console.log(document.querySelectorAll('li').length);
Text
A 2 null
3

querySelector returns the first matching element in document order, or null, so read it with ?. when it may not exist. querySelectorAll returns a NodeList that is a snapshot: the li added afterwards is not in all, which still has length 2, and a new query sees three. Both are defined in the DOM Standard's ParentNode interface.

The snapshot differs from getElementsByClassName, whose result is live and updates as the page changes. A NodeList from querySelectorAll has forEach and iteration but not map, so spread it into an array first when you need array methods. An invalid selector throws a SyntaxError, so build selectors from user input with care.

Share

More snippets

APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read
Browser

Find the closest ancestor with closest

Walk up from an element to the nearest ancestor that matches a selector with closest, which includes the element itself. Works in all modern browsers.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.