遍歷DOM樹
第一個函式: 給我根節點, 我會找到所有的子節點: forDOM(根節點) 獲取這個根節點的子節點 var children=根節點的.children 呼叫第二個函式
第二個函式: 給我所有的子節點, 我把每個子節點的名字顯示出來(children) for(var i=0;i<children.length;i++){ 每個子節點 var child=children[i]; f1(child); 給我節點, 我顯示該節點的名字 child是子節點,但是如果child里面還有子節點,此時child就是爹了 child.children&&第一個函式(child)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>遍歷DOM樹</title> </head> <body> <h1>遍歷 DOM 樹</h1> <p style="color: green;">Tip: 可以在遍歷的回呼函式中任意定制需求</p> <div> <ul> <li>123</li> <li>456</li> <li>789</li> </ul> <div> <div> <span>haha</span> </div> </div> </div> <div id="demo_node"> <ul> <li>123</li> </ul> <p>hello</p> <h2>world</h2> <div> <p>dsa</p> <h3> <span>dsads</span> </h3> </div> </div> <script> //獲取頁面中的根節點--根標簽 var root=document.documentElement;//html //函式遍歷DOM樹 //根據根節點,呼叫fn的函式,顯示的是根節點的名字 function forDOM(root1) { //呼叫f1,顯示的是節點的名字 // f1(root1); //獲取根節點中所有的子節點 var children=root1.children; //呼叫遍歷所有子節點的函式 forChildren(children); } //給我所有的子節點,我把這個子節點中的所有的子節點顯示出來 function forChildren(children) { //遍歷所有的子節點 for(var i=0;i<children.length;i++){ //每個子節點 var child=children[i]; //顯示每個子節點的名字 f1(child); //判斷child下面有沒有子節點,如果還有子節點,那么就繼續的遍歷 child.children&&forDOM(child); } } //函式呼叫,傳入根節點 forDOM(root); function f1(node) { console.log("節點的名字:"+node.nodeName); } //節點:nodeName,nodeType,nodeValue </script> </body> </html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/156528.html
標籤:JavaScript
上一篇:JS高級---復習和課程介紹
下一篇:ES6實作圖片切換特效
