Traverse a DOM tree breadth-first and return nodes in order
Given a root node of a DOM tree, write a function to traverse the tree level by level and return an array of nodes in the order they are visited. This task simulates a breadth-first search (BFS) traversal of the Document Object Model (DOM), which is particularly useful for various web development tasks, such as manipulating or querying a webpage’s structure. Traversing the DOM level by level is a breadth-first search.
The function should take a single argument: the root node of the DOM tree to be traversed. It should return an array containing the nodes in the order they were visited during the traversal. The DOM tree can be visualized as a hierarchical structure of nodes, where each node represents an element in the webpage, and its children represent the nested elements within it.
Example:
Input: Root node of a DOM tree representing the following HTML structure:
<div>
<p>Paragraph 1</p>
<div>
<p>Paragraph 2</p>
</div>
</div>
Output: [div, p (Paragraph 1), div, p (Paragraph 2)]
This example illustrates a simple case where the function starts at the root <div> node, adds it to the results array, and then proceeds to its children, adding them to the array in the order they appear, level by level. The process continues until all nodes in the tree have been visited and added to the results array.
Your task is to implement this traversal function, ensuring that it accurately reflects the breadth-first search approach and correctly captures the structure of the DOM tree.