The reason the recurring functions of the recursive function were related to the fact that you reassigned the node . Let yourself step through the function:
document -> has a child html -> has a child head -> has a child meta -> has no child, has a sibling title -> has no child or sibling head -> head has been overwritten with meta, which has a sibling title -> has no child or sibling html -> html has been overwritten with head, which has a sibling body -> has a child h1 -> has no child, has a sibling p -> has no child, has a sibling ul -> has a child li -> has no child or sibling ul -> ul has been overwritten with li, which has no sibling body -> body has been overwritten with h1, which has a sibling ...
So now you understand why rewriting a function argument is bad.
If you need a more robust approach, here's how I would write a recursive DOM traversal function:
function mostrarNodosV2(node) { if (node == null) { return; } console.log(node.nodeName); mostrarNodosV2(node.firstElementChild); mostrarNodosV2(node.nextElementSibling); } mostrarNodosV2(document);
The only difference here is that I am checking the validity of the node one recursion deeper than you were for each node, which reduces the verbosity of your approach.
source share