Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explain this DOM traversal order

Tags:

javascript

I wrote the following page as a DOM traversal demo:

<html>
    <head>
        <title>DOM Traversal</title>
    </head>
    <body>
        <h1>Sample H1</h1>
        <div id="text">
            <p>Sample paragraph</p>
        </div>
    </body>
    <script>
        // Traversing the DOM tree
        "use strict";

        var node = document.body;

        while(node) {
            console.log(node);
            node = node.lastChild;
        }
    </script>
</html>

Surprisingly, the output I'm getting is the body tag followed by the script tag. How is this possible? Isn't the script tag a sibling of the body tag? Also, why aren't the child nodes of body being traversed?

like image 634
ankush981 Avatar asked Mar 24 '26 05:03

ankush981


2 Answers

You cannot add your script element outside of the head or body elements. The browser is auto-correcting your HTML, moving the script into the end of your body, which explains the result you are getting.

The html element may only contain the head and body elements as its children. Anything else must be placed within these two elements.

like image 60
iMoses Avatar answered Mar 26 '26 20:03

iMoses


On top of what iMoses said, your script block will run before the entire document is parsed, as it doesn't wait on the domReady event. This seems to cause a race condition.

If you leave your script where it is, but wait for domReady, you get a slightly different result (albeit still not what you want).

EDIT: change your script to output "node.outerHTML" instead, and you will see that the script block gets moved or rather duplicated into the body. Without waiting for document ready, you end up with two script blocks while the script is running - one is your original, the other one at the end of the body as iMoses pointed out. Waiting for document ready, you will find that only the (moved) one inside the body remains.

like image 40
UweB Avatar answered Mar 26 '26 19:03

UweB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!