深度遍历节点

function tranverse(el,lv){

	if(el.nodeType == 1 || el.nodeType == 9){
		var name = el.nodeName.toString() + "<br />";
		lv.push('>');
		for(var i=0,len = el.childNodes.length; i < len;i++){
			name =  name +  tranverse(el.childNodes.item(i),lv);
		}
		lv.pop('>');
		return lv.join('') +name ;
	}
	return '';
}

document.getElementById('result').innerHTML = tranverse(document,[]);

/*另外,也可以使用内置方法 createTreeWalker,要求浏览器支持DOM level2,IE版本>=9.
参考:https://developer.mozilla.org/en/DOM/document.createTreeWalker
 http://www.w3.org/TR/DOM-Level-2-Traversal-Range/traversal.html#Traversal-NodeFilter
http://msdn.microsoft.com/en-us/library/ie/ff974360%28v=vs.85%29.aspx
*/
var treeWalker = document.createTreeWalker(
    document.body,
    NodeFilter.SHOW_ELEMENT,
    { acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } },
    false
);
var nodeList = [];
while(treeWalker.nextNode()) nodeList.push(treeWalker.currentNode);

你可能感兴趣的:(遍历)