The JavaScript querySelector() method
The querySelector() method returns the first element that matches a CSS selector, or null if nothing matches. document.querySelector(".btn") grabs the first element with class btn. Because it takes any CSS selector, it's the most flexible way to find an element. For all matches, use querySelectorAll().
Overview
querySelector() finds an element using a CSS selector — the same syntax you already use for styling. document.querySelector("#main .card"), querySelector("input[type=email]"), querySelector("button.primary"): anything you can target in CSS, you can find here. That flexibility is why it has largely replaced the older, single-purpose lookup methods.
It returns the first match in document order, or null if there's no match at all. That null is important — calling a method on it (querySelector(".missing").textContent) throws the classic "Cannot read properties of null" error. Check the result first, or use optional chaining (el?.textContent).
You can also call it on an element, not just document, to search only within that element's subtree — card.querySelector(".title") scopes the search. For an ID lookup, getElementById() is marginally faster and reads clearly, but querySelector("#id") works too. When you need every match rather than the first, reach for querySelectorAll().
Syntax
const el = document.querySelector(selectors)
document.querySelector(".btn")
document.querySelector("#main input[type=email]")
card.querySelector(".title") // scoped to an element
Parameters
The querySelector() method accepts the following parameters.
| Parameter | Description |
|---|---|
selectors |
A string containing one or more CSS selectors. The first matching element is returned. |
Example
<p class="greeting">Original text</p>
<script>
const el = document.querySelector('.greeting');
if (el) {
el.textContent = 'Found and changed by querySelector!';
el.style.color = '#1c7ce9';
}
</script>
Best practices
- Always handle the
nullcase — a missing element returnsnull, and using it throws. - Scope searches by calling it on an element (
parent.querySelector(...)) instead of always ondocument. - Use any CSS selector you like — class, attribute, descendant, pseudo-class all work.
- For every match, use querySelectorAll(); for a single ID, getElementById() is also fine.
Frequently asked questions
What does querySelector() return?
null if none match.What is the difference between querySelector() and getElementById()?
querySelector() accepts any CSS selector, so it's more flexible (and can also match an ID with "#id").What is the difference between querySelector() and querySelectorAll()?
querySelector() returns the first match (or null); querySelectorAll() returns a list of all matches.Why do I get "Cannot read properties of null"?
null. Check the element exists first, or use optional chaining: el?.textContent.