<!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>
如对本文有疑问, 点击进行留言回复!!
网友评论