<!DOCTYPE HTML> <html> <head> <title>遍历节点树</title> <meta charset="utf-8"/> <script src="js/3_2.js"></script> </head> <body> <span>Hello World !</span> <ul id="nav"> <li>娱乐</li> <li>电视剧 <ul> <li>内地</li> <li>韩剧</li> <li>美剧</li> </ul> </li> <li>电影</li> </ul> </body> </html>
function getChildren(parent){ console.log(parent.nodeType==3?parent.nodeValue:parent.nodeName); for(var i=0,len=parent.childNodes.length;i<len;i++){ console.log(parent.childNodes[i].nodeName); getChildren(parent.childNodes[i]) } } window.onload=function(){ getChildren(document.body);
nodeType: 获得当前节点的类型,返回的是一个数字(专门判断不同节点类型)
ELEMENT_NODE: 1
TEXT_NODE: 3
ATTRIBUTE_NODE: 2
DOCUMENT_NODE: 9
时间: 2024-10-27 12:44:04