I got this code while searching, however, I would like it to convert from recursive function to loop using for or while etc. This code is about selecting all childnodes of Body in DOM(Javascirpt) and print on console.
<script>
function traverse(target, callback){
if(target.nodeType === 1){
callback(target);
var c = target.childNodes;
for(var i=0; i<c.length; i++){
/* recursive function here */
traverse(c[i], callback);
}
}
}
traverse(document.querySelector('body'), function(elem){
console.log(elem);
});
</script>
Could you give me some tips? Thanks in advance:)
document.querySelectorAll( 'body *' ).forEach( console.log )would do the trick as well.whileloop would not allow this, as going back up the tree to the next element isn't exactly easy in such a situation.