<!doctype html> <html> <body> <div id=1><div id=6></div></div> <div id=2><div id=7><div id=11></div></div></div> <div id=3><div id=8></div><div id=12></div></div> <div id=4><div id=9><div id=13></div><div id=14></div></div></div> <div id=5><div id=0></div><div id=15><div id=16></div></div></div> <script> var walker = function(){ var counter = 0; var children = document.body.childNodes; var each = function (obj, fn, scope) { for (var i = 0, n = obj.length ; i < n; i++) { if (fn.call(scope || obj[i], obj[i], i, obj) === false ) { break; } } }; var nodesHandler = function(node, i){ if(node.nodeType == 1 && node.tagName != "SCRIPT") { counter++; alert(node.id); each(node.childNodes, nodesHandler) } }; each(children, nodesHandler); alert("counter : " + counter); } walker(); </script> </body> </html>