直接上代码吧,想了有半天,看来学的算法忘得差不多了:

dfs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<p>
hello world1
<span>
p1
<span>p11</span>
</span>
</p>
<p>hello world2</p>
<script>
function bianli(){
var html = document.documentElement;
function dfs(node){
// if(node == null) //回退到没有节点
// return;
if(node.nodeType!=1){ //去掉非元素节点,比如属性节点text
dfs(node.parentNode);
return;
}
if(!!node.getAttribute('visited')){ //获取在元素子元素同级的没被访问过的元素,接着访问左子树
var hasChildNotVisited = false;
Array.prototype.forEach.call(node.childNodes, function(node, index){
if(node.nodeType==1 && !node.getAttribute('visited')){
hasChildNotVisited = true;
dfs(node);
}
});
if(!hasChildNotVisited){
dfs(node.parentNode);
}
}
node.setAttribute('visited', 'true');
console.log(node.nodeName);
var fc = node.firstChild;
if(!!fc)
dfs(fc);
else
dfs(node);
}
dfs(html);
}
bianli();
</script>
</body>
</html>

bfs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div>
<div>
<p>
<span></span>
</p>
</div>
</div>
<script>
function bianli(){
var html = document.documentElement;
var temp = [html];
function bfs(index){
if(!temp[index])
return;
console.log(temp[index].nodeName);
Array.prototype.forEach.call(temp[index].childNodes, function(node, i){
if(node.nodeType==1){
temp.push(node);
}
});
bfs(++index)
}
bfs(0);
}
bianli();
</script>
</body>
</html>

做个记录