0

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:)

8
  • 2
    The main idea of having a recursion is, usually, the fact that you don't know the depth of it. So if you know how deep can go target.childNodes, you can use for instead, but it will be for(for(... The other thing, is for better readability you can use this.childNodes.forEach(callback); Commented Nov 6, 2019 at 9:51
  • 2
    For your goal here, document.querySelectorAll( 'body *' ).forEach( console.log ) would do the trick as well. Commented Nov 6, 2019 at 9:53
  • 2
    The reason you need recursion for something like this is, like Animus said, you don't know how deep this rabbit hole goes, so you need to be able to call the function for as long as there are deeper layers to explore. A while loop would not allow this, as going back up the tree to the next element isn't exactly easy in such a situation. Commented Nov 6, 2019 at 9:58
  • 1
    You are welcome. somethinghere gave a better advice I think. Which is selecting every element with particular selector, however, you should have a selector, or their collection for it. Commented Nov 6, 2019 at 9:58
  • 1
    One can only loop a pre-defined array. As you don't know anything about the hierarchy of the elements, you can't iterate over them with a loop Commented Nov 6, 2019 at 9:59

1 Answer 1

1

You can query the target element for all its children and iterate over them

function traverse(target, callback)
{
   var nodes = target.getElementsByTagName('*');
   callback(target);
   for(var i=0;i<nodes.length;i++)
   {
      callback(nodes[i]);
   }

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.