1

I'm having a problem traversing the DOM tree. Here's my code:

HTML:

<!DOCTYPE html>
<html lang="en">

<head>
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <script src="main.js"></script>
   <title>DOM Traversing</title>
</head>

<body>
    <ol>
        <li>
            <a href="">One</a>
            <ul>
              <li><a href="">1.1</a></li>
              <li><a href="">1.2</a></li>
              <li><a href="">1.3</a></li>
            </ul>
       </li>
       <li><a href="">Two</a></li>
       <li><a href="">Three</a></li>
       <li><a href="">Four</a></li>
    </ol>
</body>

</html>

Javascript:

var rootNodeChildren = document.childNodes;
var rootNodeChild;

for (var i = 0; i < rootNodeChildren.length; ++i) {
    rootNodeChild = rootNodeChildren[i];
    console.log(rootNodeChild);
    console.log(rootNodeChild.childNodes.length);
    for (var j = 0; j < rootNodeChild.childNodes.length; ++j) {
        console.log(rootNodeChild.childNodes[j]);
    }
}

This this the result of the following code:

enter image description here

The document object has 2 children

  1. DOCTYPE html
  2. html tag

The html tag should have 2 children as well.

  1. head tag
  2. body tag

But the output shows that html tag has only one child i.e. head tag

Can someone please explain why that is?

In the example, the HTML is not relevant but I intend to write a recursive function to traverse all elements of DOM tree.

1
  • I can't reproduce it. Try logging rootNodeChild.childNodes[i].tagName rather than the object. Also, use children instead of childNodes, so you skip the text nodes.
    – Barmar
    Commented Sep 1, 2017 at 22:04

1 Answer 1

4

This is due to script execution time.

The script runs before the body element is present on the DOM: therefore it correctly tells you that the head element is the only child...at the time.

Move your script towards the bottom and it'll include the body element in your count.

1
  • 2
    …or execute the function onload.
    – Bergi
    Commented Sep 1, 2017 at 22:19

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.