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?