原生JS求DOM樹的最大深度


題目分析:求dom樹的最大深度

  1. 以html標簽為根結點;
  2. 從根節點出發,一層一層找子節點;
  3. 對於同級節點來說,只需要返回該級子節點返回的最大子節點( node.children )樹。
<!DOCTYPE html>
<html lang="en">
  <body>
    <div>
      <div>
        <p>
          <span><span></span></span>
        </p>
        <p></p>
        <p><span></span></p>
      </div>
    </div>
  </body>
</html>
<script>
    // 求dom樹的最大深度
    const getDepth = node => {
      if (!node.children || node.children.length === 0) {
        return 1
      }
      const maxChildrenDepth = [...node.children].map(v => getDepth(v))
      return 1 + Math.max(...maxChildrenDepth)
    }
    console.log(getDepth(document.documentElement))
</script>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM