JavaScript querySelector and querySelectorAll Guide
JavaScript provides two primary methods for targeting elements in the
Document Object Model (DOM) using CSS selectors:
querySelector and querySelectorAll. These
versatile methods allow developers to select single or multiple elements
using standard CSS syntax, including tag names, classes, IDs,
attributes, and complex combinators. This guide explains how both
methods function, their key differences, and how to use them
effectively.
Understanding
querySelector
The document.querySelector() method searches the DOM and
returns the first element that matches a specified CSS
selector. If no matches are found, it returns null.
Syntax
const element = document.querySelector(cssSelector);Examples
- By ID:
document.querySelector('#main-heading') - By Class:
document.querySelector('.btn-primary') - By Tag Name:
document.querySelector('p') - By Attribute:
document.querySelector('input[type="text"]') - Complex Selector:
document.querySelector('ul.nav > li:first-child a')
Because querySelector stops searching as soon as it
finds the first matching node, it is optimized for finding unique
elements.
Understanding
querySelectorAll
The document.querySelectorAll() method searches the DOM
and returns all elements matching the specified CSS
selector. The result is returned as a static NodeList. If
no elements match, it returns an empty NodeList.
Syntax
const elements = document.querySelectorAll(cssSelector);Working with the Returned
NodeList
Unlike older collection methods like
getElementsByTagName, a NodeList supports the
built-in .forEach() method:
const cards = document.querySelectorAll('.card');
cards.forEach((card) => {
card.classList.add('highlight');
});To use standard array methods like .map(),
.filter(), or .reduce(), you can convert the
NodeList into a standard JavaScript array using the spread
operator:
const buttons = [...document.querySelectorAll('button')];Key Differences
| Feature | querySelector |
querySelectorAll |
|---|---|---|
| Return Value | First matching Element or
null |
Static NodeList (empty if
none match) |
| Use Case | Single element retrieval | Multiple element retrieval |
| Iteration | Not iterable directly | Iterable using forEach() or
for...of |
| Performance | Stops after the first match | Scans the full targeted DOM tree |
Scoped Element Queries
Both methods can be called on individual DOM elements rather than the
global document object. This restricts the search scope to
the descendants of that specific container:
const sidebar = document.querySelector('#sidebar');
const sidebarLinks = sidebar.querySelectorAll('a');In this example, only anchor tags located inside the
#sidebar element are selected.
Static vs. Live Collections
The NodeList returned by querySelectorAll
is static. This means that if elements are added to or
removed from the DOM after the query is executed, the
NodeList will not automatically update to reflect those
changes.