DEV Community

jser
jser

Posted on • Updated on

BFE.dev #104. Traverse DOM level by level

BFE.dev is like a LeetCode for Front End developers. I’m using it to practice my skills.

Alt Text

This article is about the coding problem BFE.dev#104. Traverse DOM level by level

Analysis

Level by level, so initial level would be

[div]
Enter fullscreen mode Exit fullscreen mode

then the next level is

[p, p, div]
Enter fullscreen mode Exit fullscreen mode

then the next level is

[button, a, p, div]
Enter fullscreen mode Exit fullscreen mode

We could just keeping pulling the elements from left, and push their children in from right, right ? This is a queue.

Show me the code

The implementation is BFS, not difficult, and we are only required to collect the elements, so doesn't need to care about the boundary of each level.

/**
 * @param { HTMLElement } root
 * @returns { HTMLElement[] }
 */
function flatten(root) {
  if (root === null) return []

  const queue = [root]

  const result = []

  while (queue.length > 0) {
    const head = queue.shift()
    result.push(head)
    queue.push(...head.children)
  }

  return result
}
Enter fullscreen mode Exit fullscreen mode

Passed

This is a fairly simple problem.

Alt Text

Hope it helps, you can have a try at here

Top comments (0)