二叉树节点遍历,主要是通过递归方式进行查找,因为层级不定,所以用递归能遍历所有节点,但效率不高,数据量大时会出问题.
html代码
<div class=“demo”>
<ul>
<li></li>
<li>
<ul>
<li></li>
<li></li>
<li>
<ul>
<li></li>
<li></li>
<li></li>
</ul>
</li>
</ul>
</li>
<li></li>
<li><span></span>
<span></span></li>
</ul>
</div>
js 代码
//第一种递归遍历
var demo = document.querySelector(".demo");
function getChild(parent){
var temp = parent.children;
console.log(parent.nodeName);
for(var i = 0 ; i < temp.length ; i++){
getChild(temp[i]);
}
}
getChild(demo);
//第二种递归遍历
function getchild1(parent){
var nodeIterator = document.createNodeIterator(parent,NodeFilter.SHOW_ELEMENT,null,false);
var node = null;
while((node = nodeIterator.nextNode()) != null){
console.log(node.nodeName );
}
}
getchild1(demo);