All three selector methods parse a CSS selector and throw a SyntaxError DOMException if it's invalid.
querySelector(sel)returns the first matching descendant in tree order, ornull.querySelectorAll(sel)returns all of them as a staticNodeList.closest(sel)walks up: the element itself first, then each ancestor, and returns the first that matches, ornull.matches(sel)returns whether this element matches. (webkitMatchesSelector()is a legacy alias.)
The trap is scope. el.querySelector('section p') matches the selector against the whole tree and only requires the result to be inside el; the section can be outside it. To anchor the selector at el, start with :scope: el.querySelector(':scope > p'). In closest() and matches(), :scope is the element itself.
Selectors stop at shadow roots: they match within one tree, so document.querySelector() doesn't find nodes inside a component's shadow root, and closest() doesn't climb out of one.
closest() with matches() is the core of event delegation: one listener on a container, then event.target.closest('.del') to find the control that was clicked.
TreeWalker (document.createTreeWalker(root, whatToShow, filter)) visits nodes, not just elements. whatToShow picks node types (NodeFilter.SHOW_TEXT, SHOW_COMMENT, SHOW_ELEMENT…), and the optional filter returns:
FILTER_ACCEPT: visit the node.FILTER_SKIP: skip the node but still visit its children.FILTER_REJECT: skip the node and its subtree.
You step with nextNode(), parentNode(), firstChild() and friends; currentNode is the position, and it starts at root, which nextNode() never returns. The walker follows the tree as it is when you step, so it handles mutations during the walk. Use it for things selectors can't express: collecting text nodes for highlighting, finding comments, or pruning whole subtrees. NodeIterator is the flat variant; for it, FILTER_REJECT acts like FILTER_SKIP.