DFS and BFS on HTML nodes

potential problem?

by Augustus Yuan

HTML

<div class="a">
    <div class="aa">
        <span class="aaa">
        </span>
        <span class="aab">
        </span>
    </div>
    <div class="ab">
        <span class="aba">
        </span>
        <span class="abb">
        </span>
    </div>
</div>

JavaScript

function dfsRecursiveOnHTML(element) {
  console.log(element);
  Array.from(element.children).forEach(function(child) {
    dfsRecursiveOnHTML(child);
  });
}

// Implement DFS with a Stack
// Note only really different is the order the children are processed
// but other than that it is still DFS
function dfsStackOnHTML(element) {
  var stack = [];
  stack.push(element);
  while (stack.length > 0) {
    var el = stack.pop();
    console.log(el);
    Array.from(el.children).forEach(function(child) {
      stack.push(child);
    });
  }
}

function bfsOnHTML(element) {
  var queue = [];
  queue.push(element);
  while (queue.length > 0) {
    var el = queue.shift();
    console.log(el);
    Array.from(el.children).forEach(function(child) {
      queue.push(child);
    });
  }
}

console.log('dfsRecursiveOnHTML')
dfsRecursiveOnHTML(document.getElementsByClassName('a')[0]);

console.log('dfsStackOnHTML');
dfsStackOnHTML(document.getElementsByClassName('a')[0]);

console.log('bfsOnHTML')
bfsOnHTML(document.getElementsByClassName('a')[0]);