I'm currently doing this small tutorial on accessing the DOM. Right at the bottom of the page, there's a small excersise on creating a function to go through all the nodes in the DOM and get the next node. I've got the code working, but I'm not sure exactly HOW it's working. This is less to do with the DOM and more to do with if/while loops.
This is the code:
nextNode = function(node) {
if (node.firstChild) {
return node.firstChild;
}
while (node) {
if (node.nextSibling) {
return node.nextSibling;
}
node=node.parentNode;
};
return node;
};
My questions are:
What is the first step that this function will take? For instance, it first checks if there's a child node for the selected node. If there is, it'll 'return' it. Shouldn't this end the function? I thought returning was a way to break out of a function? Why does it continue?
When it continues on to the while loop, it checks if there's a next sibling. It 'returns' this too. What is it returning it to? It then jumps to the parent node, and then checks again.
I hope my question makes sense. I'm just trying to understand the steps that are being taken during the execution of this function.
The return works as you suppose it does - it terminates the function call completely. What your function does is basically a single step in deep DOM tree walkthrough:
null, (because it exits the while loop only when node isn't defined).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With