使用js遍历dom(广度遍历 & 深度遍历)

75 阅读1分钟

dom结构

<div class="parent">
    <p class="1">
      <span class="11"></span>
    </p>
    
    <ul class="2">
      <li class="21">
        <a href="xxx"></a>
      </li>
      <li class="22"></li>
    </ul>
</div>

广度遍历

广度遍历dom节点,打印节点的tag

期望的打印顺序:div、p、ul、span、li、li、a

let node = document.querySelector('.parent')

function fn(node) {
  let stack = [node]
  while(stack.length) {
    const currenNode = stack.shift()
    console.log(currenNode.tagName)
    
    const child = currenNode.children
    for (let i = 0; i < child.length; i++) {
      stack.push(child[i])
    }
  }
}

执行结果:

image.png

深度遍历

广度遍历dom节点,打印节点的tag

期望的打印顺序:div、p、span、ul、li、a、li

let node = document.querySelector('.parent')

function fn(node) {
  let stack = [node]
  while(stack.length) {
    const currentNode = stack.pop()
    console.log(currentNode.tagName)

    const child = currentNode.children
    for (let i = child.length - 1; i >= 0; i--) {
      stack.push(child[i])
    }
  }
}

执行结果:

image.png

总结

  • 广度遍历使用shift,每次取stack中的第一项;放置children进入stack时,从0到n的顺序push
  • 深度遍历使用pop,每次取stack中的最后一项;放置children进入stack时,从n到0的顺序push