利用javascript可以遍历DOM树,这篇文章介绍用获取一个DOM元素的所有父节点和获取一个DOM元素的所以子孙节点。
1.获取所有父节点。用递归的方法,用parentNode属性。
<!DOCTYPE html> <html lang=”en” > <head> <title>getParents</title> </head> <body > <div > <div id=”test”> </div> <div></div> </div> <script type=”text/javascript”> var getParents=function(id){ var dom=id.parentNode; while(dom.tagName!=null){ document.write(dom.tagName); dom=dom.parentNode; } return dom; } getParents(test); </script> </body> </html>
运行结果(chrome、firefox、IE9):DIVBODYHTML
2.遍历所有子孙节点。
<!DOCTYPE HTML> <html> <head> <meta charset = “utf-8″/> <title>getChildren</title> </head> <body> <div>
I am in second floor <div> I am in second floor</div> </div> <div>
1 <div>
I am in second floor <div> I am in third floor</div> </div> </div> <div>1</div> <div>1</div> <div>1</div> <div id=”test”> <div>
I am in second floor
</div> <div>
I am in second floor
</div> </div> <script type=”text/javascript”> var node; node = document.getElementsByTagName(‘body’); //深度遍历 function getChildren(node,f){ //f表示第几层,根元素为第0层 if(node.nodeType!=3){ console.log(“nodename: “+node.nodeName); console.log(“nodetype: ” + node.nodeType); console.log(“the “+f+”th floor”); var childlist = node.childNodes; console.log(childlist); var length; length = childlist.length; if(childlist.length>0){ var f = f+1; for(var i=0;i<childlist.length;i++){ getChildren(childlist[i],f); } } }else if(node.nodeValue.length > 1){ //因为每个nodeValue都带一个换行符”%0A” console.log(“value: “+node.nodeValue); } } getChildren(node[0],0); //层次遍历DOM树 function getChildrenByLev(arr,f,Matri){ //f表示第几层,根元素为第0层,arr表示遍历起始层的节点,Matri为层次遍历输出的结果,结果以一个二维数组表示,第一个索引表示层次 if(arr.length<1)return Matri; f = f+1; Matri[f] = Matri[f] || new Array(); for(var i = 0; i < arr.length ; i++){ children = arr[i].childNodes; for(j in children){ if(children[j].nodeType == 1){ Matri[f].push(children[j]); } } } getChildrenByLev(Matri[f],f,Matri); } var levelMatri = new Array(); levelMatri[0] = new Array(); levelMatri[0][0] = node[0]; getChildrenByLev(node,0,levelMatri); console.log(levelMatri); </script> </body> </html>
深度遍历的结果如图(注意:截图不全):
层次遍历的结果如图: