The page is a tree: DOM querying and traversal, explained plainly
The page is a tree, the menu its branches, the order cards its leaves. This guide follows MDN's querySelector, querySelectorAll, closest, matches, parentElement, and children references: taking the first and taking all, searching from a container, walking up, testing in place, parents and children, escaping, and live lists.

First, the boundaries of this guide. The site already has a practical guide to classes and the prototype chain, about how objects are built; a practical guide to destructuring assignment, about how objects are taken apart; a practical guide to array methods, about how to process a list you hold; and a practical guide to search-box debouncing, about how input-box interaction is written. This guide is about none of those. It is about one thing only: the page is already there, and you need to find the node you want in the DOM tree and walk along the tree from there. The "Greenstone Cafe" used below is still the same fictional practice project: a small web tool that takes orders for a street-side cafe. This time it is about its order page: the page holds a menu list, order cards, and category buttons, and finding nodes, filtering nodes, and walking up to a card are all DOM querying and traversal work. Every operation, code sample, and number built around it was invented to explain the technique, not a real record. All syntax and behavior of DOM querying and traversal comes from six MDN reference pages — Document: querySelector() method, Document: querySelectorAll() method, Element: closest() method, Element: matches() method, Node: parentElement property, and Element: children property — see each article's meta information and evidence record for sources. The documentation's own examples, such as an element with the class myclass, an input named login, three nested divs from div-01 to div-03, and a list of three birds, are the documentation's examples, not a real page.
Step 1: The page is a tree, and document is the entrance
When the browser reads a page in, it turns it into a tree: html is the trunk, head and body are two big branches, and below them come div, ul, and li, one layer inside another. A tree has direction: the root is at the top and the leaves at the bottom, a parent and a child are in a containing relationship, and siblings sit side by side under the same parent. Finding a node means walking in these three directions: down with querySelector, up with closest(), and in place with matches() — the steps below take them one at a time. document is the entrance to this tree, and starting from the entrance is the most common way to find a node. document.querySelector(".myclass") means: find the first element in the whole tree whose class is myclass. An element can be an entrance too: when a container element calls querySelector, it searches only inside its own subtree — step 6 covers that in detail. The cafe's order page thinks this way: the menu list is a ul, each dish inside it is an li, and each order card is a div; to change one dish, find it in the tree first, then act. Remember the first sentence: the page is a tree, document is the entrance, and finding a node is finding it in the tree.
Step 2: querySelector takes only the first match — no match gives null
querySelector(selectors) returns only the first matching element. MDN's example is: const el = document.querySelector(".myclass"), which returns the first element in the document with the class myclass. When there is no match, it does not throw; it returns null. Taking a property or calling a method on null throws a TypeError at once, and the page stops there. So check the result for emptiness first: const el = document.querySelector("#order-card"); if (!el) return; or if (el) { el.textContent = "Ordered"; }. The cafe's order page stepped into this trap: after the promotion ended, the "today's special" block was removed from the page, but the code still ran document.querySelector("#special").textContent — the block was gone, querySelector gave null, and reading textContent threw, blanking the whole order page. Remember the test: always ask first of a querySelector result — is it an element, or null?
Step 3: The selector is a CSS selector — if you can write styles, you can find nodes
The argument to querySelector is a CSS selector string, so anyone who can write CSS can find nodes. MDN's examples build up layer by layer: first const el = document.querySelector(".myclass"), taking the first element with the class myclass; then const el = document.querySelector("div.user-panel.main input[name='login']"), taking the first input named login inside a div whose classes are both user-panel and main; and it can also negate: const el = document.querySelector("div.user-panel:not(.main) input[name='login']"), taking the input whose parent div has user-panel but not main. The combinators matter too: a comma means "or" — div.note, div.alert matches either one; a space means descendant, so any input at any depth inside the div counts; a greater-than sign means direct child, so div.highlighted > p takes only a p sitting directly underneath, never one a layer further down. Classes, ids, attributes, descendants, children, and :not() are all ready-made CSS spellings. The cafe's order page finds things this way: document.querySelector("ul.menu li[data-dish='latte']") — the item in the menu list whose dish attribute is latte — located in one line. Remember the test: the more specific the selector, the more precise the hit; when you can locate by attribute, do not rely on class alone.
Step 4: querySelectorAll takes them all, in document order
To take all of them instead of one, use querySelectorAll. It returns a non-live NodeList holding one Element object for each element that matches; when nothing matches, you get an empty list, not null. The elements in the list are in document order — MDN's own words are that parents come before children, and earlier siblings before later siblings. MDN gives four examples: document.querySelectorAll("p") takes all p elements in the document; document.querySelectorAll("div.note, div.alert"), with a comma, takes all divs whose class is note or alert; document.querySelectorAll("iframe[data-src]") takes all iframes carrying a data-src attribute; and document.querySelectorAll("li[data-active='1']") takes all list items whose data-active attribute has the value 1. The cafe's order page takes things this way: document.querySelectorAll("ul.menu li"), all the dishes in the menu list, in one call. Remember the test: take all with querySelectorAll, no match means an empty list, and the order is the document order.
Step 5: A NodeList is not an array — but it can be examined like one
The NodeList that querySelectorAll returns can, MDN says, be examined just like any array: a length of 0 means nothing was found, elements can be reached by index, and common looping statements work. MDN's example is: const highlightedItems = userList.querySelectorAll(".highlighted"); highlightedItems.forEach((userItem) => { deleteUser(userItem); }) — forEach works straight away. But it is not an array, and it is not live: nodes added to the page later do not join it; it is frozen at the moment of the query. To use array methods such as map or filter, convert it into a real array first — how to process a list once it is a real array belongs to the array methods guide, not this one. The cafe's order page is written this way: first const items = document.querySelectorAll("ul.menu li"), then items.forEach((item) => { item.classList.remove("sold-out"); }), clearing every sold-out mark in one line. Remember the test: a NodeList can be counted, indexed, and looped with forEach; it is not live, and it is not a real array.
Step 6: Start from a container to narrow the search — fewer false hits
querySelector and querySelectorAll are not only on document; any element can call them, and then the search covers only its own subtree. MDN's example is: const container = document.querySelector("#test"); const matches = container.querySelectorAll("div.highlighted > p"), taking the direct-child p elements of divs with the class highlighted inside the container whose id is test. And another: const container = document.querySelector("#user-list"); const matches = container.querySelectorAll("li[data-active='1']"), searching only inside the user list. The smaller the scope, the fewer the false hits: searching the whole document for "li" also counts the navigation bar and the footer; searching for "li" from the menu container counts only dishes. The container itself must be found and checked first: calling querySelectorAll on a container that is null throws all the same, so the order is to take the container, check it, and only then search below it. The cafe's order page is written this way: first const menu = document.querySelector("#menu"), then menu.querySelectorAll("li"), and not one li from the category buttons gets in. Remember the test: fix the container first, then search inside it; a smaller scope means fewer mistakes.
Step 7: Walk up with closest() — it starts from the element itself
To find an ancestor from an element, use closest(). MDN puts it this way: the closest() method traverses the element and its parents, heading toward the document root, until it finds a node that matches the specified CSS selector; it counts the element itself, so the first one found is the nearest; if there is no such element, null is returned; an invalid selector throws a SyntaxError. MDN's example is three nested divs: div-01 wraps div-02, and div-02 wraps div-03. Starting from div-03: el.closest("#div-02") gives div-02; el.closest("div div") gives div-03, because it is itself a div inside a div; el.closest("article > div") gives div-01; and el.closest(":not(div)") gives article. The cafe's order page uses it this way: when an order button is tapped, event.target.closest(".order-card") finds which order card it belongs to, and then the code changes that card's state — no matter how many layers deep inside the card the button sits. Remember the test: walk up with closest(); it starts from the element itself, the nearest match wins, and no match gives null.
Step 8: Test in place with matches() — it only answers true or false
To know whether an element would be selected by a selector, do not search again — ask the element itself, with matches(). MDN puts it this way: the matches() method tests whether the element would be selected by the specified CSS selector; it returns true if the element matches, otherwise false; a selector that cannot be parsed throws a SyntaxError. MDN's example is a list of three birds: the ul has the id birds, and of its three li children only the second has the class endangered. const birds = document.querySelectorAll("li"); for (const bird of birds) { if (bird.matches(".endangered")) { console.log(`The ${bird.textContent} is endangered!`); } } — and only "The Philippine eagle is endangered!" is logged, because only that bird really carries the endangered class. The cafe's order page filters this way: after taking all the dishes, the ones where item.matches(".sold-out") is true are marked "sold out", and the rest are left alone. Remember the test: filter one element with matches(); it only answers true or false.
Step 9: Parents and children — parentElement and children each cover one direction
One step up and one layer down each have a ready-made property. parentElement returns the DOM node's parent Element, or null if the node either has no parent, or its parent is not a DOM Element. MDN's example is: const html = document.querySelector("html"); html.parentElement is null, and html.parentNode is document — html's parent node is the document, but the document is not an Element, so parentElement gives null while parentNode gives document. Going down is children: it returns a live HTMLCollection containing all of the child elements, and when the element has no element children, it is an empty list with a length of 0. MDN's example is: const myElement = document.getElementById("foo"); for (const child of myElement.children) { console.log(child.tagName); } — printing each one in turn. Note the difference from childNodes: children includes only element nodes, while childNodes takes every kind of node, text nodes and comment nodes included. The cafe's order page counts this way: menu.children.length is the number of dishes, while menu.childNodes.length also counts the text nodes produced by line breaks, and comes out too large. Remember the test: count elements with children, count all nodes only with childNodes; html's parent element is null, its parent node is document.
Step 10: A question mark in an id makes the selector throw
The HTML specification does not require attribute values to be valid CSS identifiers, but querySelector requires the selector to be valid CSS. When an id contains characters such as a question mark or a colon, building the selector by direct concatenation throws a SyntaxError. MDN's example is a div whose id is "this?element" — the question mark is not allowed in CSS identifiers. Three buttons all try to select it and change its background color: the first concatenates "#this?element" directly and errors; the second escapes the value with CSS.escape("this?element") and works; the third escapes the question mark by hand with a backslash, written as "this\\?element", and works too — note that the backslash itself must also be escaped, so two backslashes are written in the string. The cafe's order page stepped into this trap: a category id from the backend was "hot drinks: this month", the colon was never escaped, querySelector threw, and the menu could not be filtered; escaping with CSS.escape(id) before concatenating fixed it. Remember the test: a selector that is built by concatenation must be escaped first; a value from the user or the backend always goes through CSS.escape() first.
Step 11: A pseudo-element selects nothing — the list is always empty
When the specified selectors include a CSS pseudo-element, the list that querySelectorAll returns is always empty. MDN writes this warning on the querySelectorAll page itself: if the specified selectors include a CSS pseudo-element, the returned list is always empty. A pseudo-element is not a node in the DOM tree: however vividly ::before and ::after are drawn in CSS, there is no matching node in the DOM tree to find. The cafe's order page stepped into this trap: wanting the little dot in front of each menu item, it wrote document.querySelectorAll("li::before"), and the list it got was always empty, its length always 0; the dot is drawn by CSS, it is not in the DOM tree, and searching for nodes cannot reach it. Remember the test: pseudo-elements are not in the DOM tree — never put one in a node search.
Step 12: An invalid selector throws SyntaxError in both methods
querySelector and querySelectorAll behave the same here: if the syntax of the specified selectors string is not valid, a SyntaxError DOMException is thrown. An unclosed parenthesis, an unmatched quote in an attribute selector, or an illegal character mixed into the selector all produce this error. And it is not only these two methods that throw: an invalid selector throws SyntaxError in closest() and matches() too, and MDN writes that on both the closest() and the matches() pages. So every place that takes a selector string — querySelector, querySelectorAll, closest, matches — must be guarded against an invalid one. A hard-coded selector is easy to fix; a selector that is built up — taking a value from an input box, or an id from the backend, and concatenating it — must be guarded: either wrap it in try/catch, or validate and escape it first. The cafe's order page does exactly this in its search box: before user input is concatenated into a selector, it is wrapped in try/catch, and on error the page shows "nothing found" instead of letting the whole page crash with it. Remember the test: a selector that is built up must be guarded against being invalid; catch the error at the query step, and never let it blow up the page.
Step 13: There is an older way to take an element by id: getElementById
Before querySelector existed, elements were taken by id with getElementById, and MDN's examples use it everywhere: the closest() page takes the innermost div with document.getElementById("div-03"), and the children page takes a container with document.getElementById("foo"). It means the same as document.querySelector("#foo") — take one element by id; since an id is unique on a page, the result is either that one element or nothing. When it finds nothing, it gives null just like querySelector, and it must be checked for null before use all the same. When should you use it? Where you only take by id and want the intent to be obvious at a glance: document.getElementById("menu") tells the reader more plainly than document.querySelector("#menu") that you want the element whose id is menu. The cafe's order page uses it for its top-level containers: const menu = document.getElementById("menu") — one look says menu is the element on the page whose id is menu — and the finer work below is left to querySelectorAll. Remember the test: to take by id only, getElementById says it more plainly; no match still gives null, so check before use.
Step 14: Live versus non-live — be careful changing the page while looping
The two lists a query returns differ in liveness. The NodeList from querySelectorAll is non-live: MDN writes non-live right at the top of that page, meaning it is frozen at the moment of the query — nodes added to the page later do not join it. The HTMLCollection from children is live: MDN writes live on the children page, meaning it follows the page — however many children there are when you look, that is how many it holds. This difference bites when you change the page while looping: deleting nodes one by one while looping over a live children list shrinks the list as you go, the loop index falls out of step, and the next node is skipped. The safe way is to collect the nodes to change into a frozen list first: either query them with querySelectorAll and then change them, or convert children into a real array first. The cafe's order page does exactly this for "clear sold out": first const items = menu.querySelectorAll("li.sold-out") to freeze the list, then items.forEach deletes them one by one, and no matter how many are deleted, the list does not move. Remember the test: before changing the page, ask whether the list in your hand is live or frozen — looping over a live list while changing it skips items.
Step 15: 90 DOM incidents in one month — check yourself against the chart

The chart above shows a fictional month for the Greenstone Cafe project: 90 incidents related to DOM querying and traversal in total. Forgetting the null check and taking a property straight off null: 30, or 33.3%, the largest group; treating a querySelectorAll result as a live list, so the list did not follow when the page changed: 18, or 20.0%; special characters in a selector left unescaped, throwing outright: 15, or 16.7%; searching the whole document and counting nodes from other regions too: 12, or 13.3%; mixing up children and childNodes and counting text nodes as well: 9, or 10.0%; a selector with a pseudo-element returning an empty list: 6, or 6.7%. 30 + 18 + 15 + 12 + 9 + 6 = 90, and the books balance. Each group in the chart maps to a step in this guide: forgetting the null check is step 2, the live list is step 14, unescaped special characters are step 10, searching the whole document is step 6, mixing up children and childNodes is step 9, and the pseudo-element is step 11. These numbers are invented examples, meant to show at a glance that the first group is a third of the total — and that its root cause is only one thing: when querySelector finds nothing, it gives null, not an error.
Checklist: after writing code that finds nodes, tick each item
First, the page is a tree, document is the entrance, and finding a node is finding it in the tree. Second, querySelector takes only the first match, no match gives null, and the result is checked for null before use. Third, the selector is a CSS selector — classes, ids, attributes, descendants, children, and :not() are all ready-made spellings, and the more specific it is, the more precise the hit. Fourth, take all with querySelectorAll; no match means an empty list, and the order is the document order: parents before children, earlier siblings before later siblings. Fifth, a NodeList can be counted, indexed, and looped with forEach; it is not live, and it is not a real array. Sixth, fix the container first, then search inside it; a smaller scope means fewer mistakes. Seventh, walk up with closest(); it starts from the element itself, the nearest match wins, and no match gives null. Eighth, filter one element with matches(); it only answers true or false. Ninth, count elements with children, count all nodes only with childNodes; html's parent element is null, its parent node is document. Tenth, a selector that is built up goes through CSS.escape() before concatenation. Eleventh, pseudo-elements are not in the DOM tree — never put one in a node search. Twelfth, an invalid selector throws SyntaxError in both methods, so a built-up selector gets a try/catch. Thirteenth, to take by id only, getElementById says it more plainly; no match still gives null, so check before use. Fourteenth, before changing the page, ask whether the list in your hand is live or frozen: children is a live HTMLCollection, the NodeList from querySelectorAll is non-live, and looping over a live list while changing it skips items. If any item cannot be answered, go back to its section and read it again — that is worth more than memorizing ten more APIs.
Comments (0)
Sources
Related articles
Every web page makes decisions all day: a total over 100 gets a discount, zero stock shows sold out. Following MDN's Making decisions in your code — conditionals, if...else, and switch: if and else if, comparison operators, truthy and falsy, logical operators, the classic || mistake, nested if and the dangling else, switch and fall-through, the ternary operator, and guard clauses.
The main thread has to draw the page and do the accounts, so it freezes the moment the work gets heavy. A worker is another thread in another global context, and the two sides talk only through messages. Following MDN's Using Web Workers and Worker docs: new Worker, postMessage and onmessage, structured-clone copying, what a worker can and cannot do, onerror and terminate(), SharedWorker, and transferable zero-copy — with a 100-mistake breakdown from a fictional cafe order page.
setTimeout handles once, setInterval handles repeatedly — but delay only promises "at least this long": 0 is not immediate, background tabs run even later, and anything over 2147483647 overflows. Following MDN's setTimeout and setInterval docs: async return, argument passing, the delay rules, the 4 ms nesting clamp, clearTimeout and clearInterval, recursive setTimeout, lost this, and string arguments — with a 100-mistake breakdown from a fictional cafe order page.