Selecting and Traversing the DOM: querySelector, closest, matches and Node Relationships
Find your way around a web page: what the DOM tree is, Node vs Element, querySelector and querySelectorAll with CSS selectors, :scope and :has, closest and matches, getElementById and live HTMLCollections, document.forms, parent, child and sibling properties, text nodes and traversal.
kvi5hnuCode Sprout team member7 min readOn this page
When a browser loads an HTML page, it builds a tree of objects that represents it: the Document Object Model (DOM). Every element, every piece of text and every comment becomes a node in that tree, and JavaScript reads and changes the page by working with those nodes. This article covers how to find nodes; the next one covers changing them.
The examples use this markup:
<header>
<h1 id="title">Fresh Tea</h1>
<nav><a href="/">Home</a> <a href="/cart" class="nav-link active">Cart</a></nav>
</header>
<main>
<ul id="products">
<li class="product" data-id="1"><span class="name">Green</span> <button class="buy">Buy</button></li>
<li class="product sale" data-id="2"><span class="name">Black</span> <button class="buy">Buy</button></li>
<li class="product" data-id="3"><span class="name">Oolong</span> <button class="buy" disabled>Sold out</button></li>
</ul>
<form name="search"><input name="q" type="search"></form>
</main>
The outputs shown in comments were checked by running the code against this page.
The DOM tree
The tree mirrors the nesting of the HTML. document is the root. Its child is the <html> element, whose children are <head> and <body>, and so on. Each kind of node is an instance of a class:
| Class | Represents | Notes |
|---|---|---|
Node | anything in the tree | base class: parentNode, childNodes, nodeType, textContent |
Document | the whole page | document, with body, head, title, documentElement |
Element / HTMLElement | a tag | specific subclasses like HTMLInputElement, HTMLAnchorElement |
Text | text between tags | including the whitespace between elements |
Comment | <!-- ... --> |
Each HTML tag becomes an object of a matching class, with properties for its attributes (a.href, input.value, img.src) and methods inherited from Element and Node.
nodeType tells them apart: 1 for elements (Node.ELEMENT_NODE), 3 for text, 8 for comments, 9 for the document. For elements, tagName is the uppercase tag name, like "BUTTON".
Selecting with CSS selectors
The most flexible way to find elements is with a CSS selector, the same syntax stylesheets use:
document.querySelector("#title").textContent; // "Fresh Tea"
document.querySelector(".product.sale .name").textContent; // "Black"
document.querySelector(".missing"); // null
const products = document.querySelectorAll("li.product");
products.length; // 3
[...products].map((li) => li.dataset.id); // ["1", "2", "3"]
document.querySelectorAll("button:not([disabled])").length; // 2
querySelector(selector)returns the first matching element in document order, ornull.querySelectorAll(selector)returns a staticNodeListof all matches. It haslength, indexing,forEachanditem(), and it's iterable, but it isn't an array: spread it or useArray.fromformapandfilter.- An invalid selector throws a
SyntaxError.
Both methods also exist on every element, searching only inside that element:
const list = document.getElementById("products");
list.querySelectorAll(".buy").length; // 3: buttons inside the list
list.querySelectorAll(":scope > li").length; // 3: only direct children
:scope refers to the element you're calling the method on. Without it, a selector like "li span" is matched against the whole document, and the results are then limited to descendants of list.
Useful selector patterns:
| Selector | Matches |
|---|---|
#id, .class, tag | by id, class, tag name |
[data-id="2"], [href^="https"] | by attribute value (exact, prefix) |
a b, a > b, a + b, a ~ b | descendant, child, next sibling, later siblings |
:not(.x), :is(h2, h3), :first-child, :nth-child(2n) | pseudo-classes |
:checked, :disabled, :focus, :invalid | element state |
li:has(button[disabled]) | elements that contain a match, supported in all major browsers since 2023 |
closest and matches
Two methods work in the opposite direction, testing an element against a selector:
const button = document.querySelector('[data-id="2"] .buy');
button.matches(".buy:enabled"); // true: does this element match?
button.closest("li").dataset.id; // "2": nearest ancestor (or itself) that matches
button.closest("ul").id; // "products"
button.closest("form"); // null: no matching ancestor
closest is the workhorse of event delegation (article 108): from event.target, walk up to the element you care about.
Older selection methods
These predate querySelector and are still common:
document.getElementById("title"); // fastest lookup by id; returns the element or null
document.getElementsByClassName("product"); // live HTMLCollection
document.getElementsByTagName("li"); // live HTMLCollection
document.getElementsByName("q"); // NodeList of elements with name="q"
The getElementsBy... methods return live collections, which update automatically as the document changes. querySelectorAll returns a snapshot:
const live = list.getElementsByTagName("li");
const snapshot = list.querySelectorAll("li");
list.append(document.createElement("li"));
console.log(live.length, snapshot.length); // 4 3
Live collections are a classic source of bugs: removing items while looping over a live list skips elements, because the list shrinks under you. Convert with [...collection] first, or use querySelectorAll.
The document also has shortcut collections: document.forms, document.images, document.links (<a> and <area> elements with an href) and document.scripts. They can be indexed by name or id, and a form's elements collection works the same way:
document.forms.search.elements.q; // the <input name="q">
document.links.length; // 2
document.body, document.head, document.documentElement (the <html> element) and document.title are direct properties.
Moving around the tree
Once you have an element, you can step to related elements. There are two sets of properties: one that skips text nodes, and one that includes them.

| Elements only | All nodes (text, comments too) |
|---|---|
parentElement | parentNode |
children, childElementCount | childNodes |
firstElementChild, lastElementChild | firstChild, lastChild |
nextElementSibling, previousElementSibling | nextSibling, previousSibling |
list.children.length; // 3
list.childNodes.length; // 7: the whitespace between tags counts
list.firstChild.nodeType; // 3 (a Text node containing "\n ")
list.firstElementChild.dataset.id; // "1"
list.firstElementChild.nextElementSibling.dataset.id; // "2"
list.lastElementChild.parentElement === list; // true
The whitespace and line breaks you add to format HTML become text nodes, which is why the node-level properties often surprise people. Use the element versions unless you specifically need text nodes.
parentNode and parentElement differ only at the top: document.documentElement.parentNode is the document, but its parentElement is null, because the document isn't an element.
Other relationship checks:
a.contains(b)istrueifbis insidea, or isaitself.a.compareDocumentPosition(b)returns bit flags describing whetherbprecedes, follows, contains or is contained bya.
Walking a whole subtree
Recursion over children visits every element depth-first:
function outline(element, depth = 0, lines = []) {
lines.push(" ".repeat(depth) + element.tagName.toLowerCase());
for (const child of element.children) outline(child, depth + 1, lines);
return lines;
}
console.log(outline(document.querySelector("header")).join("\n"));
// header
// h1
// nav
// a
// a
The same walk can use the linked-list style instead: start with firstElementChild and follow nextElementSibling until it's null. For large documents, or when you need text nodes too, the built-in document.createTreeWalker(root, NodeFilter.SHOW_TEXT) iterates nodes of selected types without recursion. For example, it can collect all visible text into "Fresh Tea|Home|Cart|Green|Buy|...".
Performance and good habits
- Cache elements you use repeatedly in variables instead of querying them again in a loop.
- Scope queries to a container (
panel.querySelector(...)) so they're shorter and faster, and so they don't accidentally match elsewhere. - Prefer stable hooks such as
ids,data-*attributes ([data-action="delete"]) or ARIA roles over long structural selectors (div > div:nth-child(3) span), which break whenever the markup changes. - Remember that
querySelectorreturnsnullwhen nothing matches. Check for it, or use optional chaining:document.querySelector("#banner")?.remove().
Common questions
What's the difference between a NodeList and an HTMLCollection?
Both are array-like lists. querySelectorAll returns a static NodeList with forEach. children and getElementsBy... return live HTMLCollections, which have no forEach and update as the document changes. Spread either into an array for full array methods.
Why does childNodes include things I didn't write?
The whitespace and line breaks between tags are text nodes. Use children and the ...ElementChild/...ElementSibling properties to see only elements.
querySelector("#id") or getElementById("id")?
Both work. getElementById is slightly faster and doesn't need escaping for ids that contain special characters. querySelector is more flexible. Use whichever reads better; the difference rarely matters.
Can I select elements by their text?
Not with CSS selectors. Filter instead: [...document.querySelectorAll("button")].find((b) => b.textContent.trim() === "Buy").
Summary
- The DOM is a tree of
Nodeobjects: theDocument,Elements,Textand comments. querySelector/querySelectorAllfind elements with any CSS selector, on the document or within an element (:scopefor direct children).closest()walks up to a matching ancestor andmatches()tests one element; both are key to event delegation.getElementByIdis the quickest lookup by id;getElementsBy...return live collections, which change as you edit the page.- Navigate with
parentElement,children,first/lastElementChildandnext/previousElementSibling; the...Node/...Childversions include text nodes.
Practice Questions
How do you select every <li> that is a direct child of #menu, but not nested ones?
Answer
Use document.querySelectorAll("#menu > li"), or, if you already have the element, menu.querySelectorAll(":scope > li"). You can also use menu.children if the list contains only <li> elements.
This loop is supposed to remove every .ad element, but it skips some. Why?
const ads = document.getElementsByClassName("ad");
for (let i = 0; i < ads.length; i++) ads[i].remove();
Answer
getElementsByClassName returns a live collection. Each removal shrinks it, so the element that moves into position i is skipped. Use a static list:
document.querySelectorAll(".ad").forEach((el) => el.remove());
Given a click on any element inside a table, find the row's data-id value.
Answer
const id = event.target.closest("tr")?.dataset.id;
closest walks up from the clicked element to the nearest <tr>. Optional chaining handles clicks outside any row.
Why does list.firstChild.textContent print only whitespace?
Answer
firstChild includes text nodes, and the line break and indentation before the first <li> form a whitespace text node. Use list.firstElementChild to get the first element.
Previous: JavaScript Events: addEventListener, the Event Object, Bubbling, Capturing and Delegation
Next: Changing the DOM: Attributes, dataset, textContent, innerHTML and Creating Elements

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.