querySelector vs getElementById vs getElementsByClassName
Compare querySelector, getElementById, getElementsByClassName and querySelectorAll: return types, live versus static results, scope and which to use when.

The browser gives you several ways to find elements, and they differ in four ways that matter: what they accept as input, what they return when nothing matches, whether the result is a single element or a collection, and whether a collection updates itself when the page changes. This post compares getElementById, getElementsByClassName, getElementsByTagName, querySelector and querySelectorAll in current browsers, with the result of each call on one small page. The specifications are the DOM Standard and the Selectors API, and MDN documents each method.
All the examples use this document.
<ul id="menu" class="nav">
<li class="item active">Home</li>
<li class="item">Docs</li>
<li class="item">Blog</li>
</ul>
<p class="item">Footer note</p>The comparison
| Method | Input | Returns | No match | Live |
|---|---|---|---|---|
getElementById(id) | an id | one element | null | n/a |
getElementsByClassName(names) | class names | HTMLCollection | empty collection | Yes |
getElementsByTagName(name) | tag name | HTMLCollection | empty collection | Yes |
querySelector(selector) | any CSS selector | first match | null | n/a |
querySelectorAll(selector) | any CSS selector | NodeList | empty list | No |
Two things stand out. Only the query methods accept full CSS selectors, and only the getElementsBy family returns live collections.
getElementById
It finds the one element with a given id. It is a method of document only, and the id is a plain string with no #.
const menu = document.getElementById("menu");
console.log(menu.tagName);
console.log(document.getElementById("missing"));
console.log(document.getElementById("#menu"));UL
null
nullThe third call returns null because the # is part of the string, and no element has the id #menu. Ids are meant to be unique, and the browser returns the first match if they are not. getElementById is the oldest and most direct lookup, and engines optimize it with an internal id map, so it is the right tool when you hold an id.
getElementsByClassName
It takes one or more class names, separated by spaces, and returns an HTMLCollection of elements that have all of them. It is a method of both document and elements.
const items = document.getElementsByClassName("item");
console.log(items.length);
const active = document.getElementsByClassName("item active");
console.log(active.length, active[0].textContent);
const menu = document.getElementById("menu");
console.log(menu.getElementsByClassName("item").length);4
1 Home
3Calling it on an element searches only that element's descendants, which is why the last count is 3, excluding the footer paragraph. Names are class names, not selectors, so there is no dot, and "item active" means both classes.
querySelector and querySelectorAll
These take any CSS selector, including combinators, attributes and pseudo-classes. querySelector returns the first match in document order, or null. querySelectorAll returns all matches.
console.log(document.querySelector("#menu").tagName);
console.log(document.querySelector(".item.active").textContent);
console.log(document.querySelector("ul > li:last-child").textContent);
console.log(document.querySelectorAll("p.item, li.item").length);
console.log(document.querySelector(".nope"));UL
Home
Blog
4
nullThe selector language is the reason to prefer these methods: ul > li:last-child and p.item, li.item would need several getElementsBy calls and some filtering. A bad selector throws a SyntaxError, so a selector built from user input must be escaped, with CSS.escape for identifiers.
const id = "section:1";
const element = document.querySelector(`#${CSS.escape(id)}`);
console.log(CSS.escape(id));section\:1Live versus static
The getElementsBy family returns live collections. They reflect the document at the time you read them, not at the time you made the call.
const live = document.getElementsByClassName("item");
const snapshot = document.querySelectorAll(".item");
console.log(live.length, snapshot.length);
const extra = document.createElement("li");
extra.className = "item";
document.getElementById("menu").append(extra);
console.log(live.length, snapshot.length);4 4
5 4After the new element is appended, the live collection has 5 and the snapshot still has 4. A live collection is cheap to hold on to when you want an always-current view, and a hazard inside a loop that changes the tree.
const items = document.getElementsByClassName("item");
for (let i = 0; i < items.length; i += 1) {
items[i].classList.remove("item");
}
console.log(items.length);2Removing the class takes the element out of the live collection, so the next item slides into index i, and the loop skips every second element. Two items remain with the class. The fix is to copy the collection first, with Array.from(items), or use querySelectorAll, whose result does not change under you.
Scope
All of these except getElementById exist on elements as well as on document, and they search the element's subtree.
const menu = document.getElementById("menu");
console.log(menu.querySelector(".item").textContent);
console.log(menu.querySelectorAll(".item").length);
console.log(menu.querySelector("ul"));Home
3
nullThe last call is null because querySelector looks at descendants, and the menu itself is not one. A subtle trap is that the selector is matched against the whole document, and then filtered to descendants, so menu.querySelector("ul li") can match an li inside the menu when the ul is an ancestor outside it. Use :scope when you mean "relative to this element": menu.querySelectorAll(":scope > li").
Which one to use
For a single element you already have an id for, use getElementById. For anything else, use querySelector and querySelectorAll, because one syntax covers every case, results are plain static data, and the code reads like the stylesheet. Reach for getElementsByClassName only when you want a live view on purpose, and be careful with loops. For tags, querySelectorAll("a") does the same as getElementsByTagName("a") with a static result.
The speed difference exists in theory, since the specialized methods skip selector parsing, and it is not worth choosing on. Browsers cache parsed selectors and optimize common forms such as #id and .class. Choose by clarity and by whether you need a live collection, and measure only if profiling shows lookups as a cost.
Handling the empty result
The two single-element lookups return null on a miss, and using the result without a check is the most common DOM error in practice: Cannot read properties of null (reading 'addEventListener'). The cause is nearly always timing, because the script ran before the element existed, or a typo in the id or selector. Decide per call what a miss means. If the element must exist, throw a clear error naming the selector, so the failure is easy to read. If it is optional, use optional chaining, document.querySelector(".banner")?.remove(), and the code does nothing when the banner is absent.
A small helper makes the first case tidy and keeps the check in one place.
function requireElement(selector, root = document) {
const element = root.querySelector(selector);
if (element === null) {
throw new Error(`Missing element: ${selector}`);
}
return element;
}
console.log(requireElement("#menu").tagName);ULWith TypeScript, querySelector<HTMLInputElement>(".email") gives the element a specific type, and the null in the return type forces the check.
Names, forms and other older lookups
Older APIs remain for specific cases. document.getElementsByName finds elements by their name attribute and returns a live NodeList, and it is still handy for radio groups. The document.forms and form.elements collections give named access to forms and their controls, so form.elements.email finds the field named email. document.querySelector("[data-id='7']") covers attribute lookups, with no extra method. For elements that already hold a reference to a relative, closest(selector) walks up the tree to the nearest ancestor that matches, and matches(selector) tests an element against a selector, and those two are the tools that make event delegation short.
A short decision list
When you are choosing quickly, three questions settle it. Do you have an id and want one element? Use getElementById. Do you want elements by a pattern more complex than one class or tag? Use querySelectorAll. Do you need the result to track the document as it changes, without re-querying? Use a live collection, and document that choice in a comment, since the next reader will not expect it.


