Walking the DOM comes in two flavors. Depth-first dives down one branch to the bottom before backtracking. Breadth-first (BFS) fans out level by level — the root, then all its children, then all the grandchildren — which is what you want for "find the nearest matching element" or "process the tree tier by tier." BFS is powered by a queue: you take a node off the front and push its children on the back, so nodes come out in the order they were discovered.
Implement traverseDomBfs(root). Return the elements in breadth-first order — root first, then each level left to right. Visit element nodes only; a null root yields [].
function traverseDomBfs(root) {
// returns an array of elements in level-by-level order
}
// <div id=a><div id=b><div id=d/></div><div id=c/></div>
traverseDomBfs(a); // [a, b, c, d] (BFS)
// depth-first would be: a, b, d, c
node.children, skipping text/comment nodes.traverseDomBfs(null) returns [].