Traverse DOM (BFS)Loading saved progress…

Traverse DOM (BFS)

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 [].

Signature

function traverseDomBfs(root) {
  // returns an array of elements in level-by-level order
}

Examples

// <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

Notes

  • Queue, not stack — take from the front, add children to the back. (A stack would give you depth-first.)
  • Level by level — the root is level 0, its children level 1, and so on; within a level, left to right.
  • Elements only — iterate node.children, skipping text/comment nodes.
  • Null-safetraverseDomBfs(null) returns [].
Loading editor…