直接上代码吧,想了有半天,看来学的算法忘得差不多了:
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.nodeType!=1){ 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>
|
做个记录