JavaCake
JavaCake

Reputation: 4115

childNodes for documentElement returns one null

I am performing some simple JS test for traversing and i was wondering why my documentElement consist of one null object?

<html>
    <head>
        <title>My document</title>
    </head>
    <body>
        <h1>Some header</h1>
        <p id="pID">Some paragraph</p>
        <p name="pNAME">Another paragraph/p>
    </body>
</html>
<script type="text/javascript">
    var rootElement = document.documentElement;
    var childNodes = rootElement.childNodes;

    for (var i = 0; i < childNodes.length; i++) {
      document.write(childNodes[i].localName);
      document.write("<br>");
    }
</script>

It returns head, null, body. But why is there 3 childNodes in the rootElement?

Upvotes: 1

Views: 1285

Answers (2)

Minko Gechev
Minko Gechev

Reputation: 25692

If you list only the objects instead of their localName you will see:

[object HTMLHeadElement]
[object Text]
[object HTMLBodyElement]

So you receive null for the localName of the text node. To fix this you need children instead of childNodes:

<script type="text/javascript">
    var rootElement = document.documentElement;
    var childNodes = rootElement.children;

    for (var i = 0; i < childNodes.length; i++) {
      document.write(childNodes[i]);
      document.write("<br>");
    }
</script>

Here is demo in JSFiddle.

Upvotes: 2

Vassilis Barzokas
Vassilis Barzokas

Reputation: 3252

The new line between </head> and <body> is considered as text ([object Text]), so it's .localName attribute is null.

If you try this it should output only 2 elements

    <html>
    <head>
        <title>My document</title>
    </head><body>
        <h1>Some header</h1>
        <p id="pID">Some paragraph</p>
        <p name="pNAME">Another paragraph</p>
    </body>
</html>

    <script type="text/javascript">
        var rootElement = document.documentElement;
        var childNodes = rootElement.childNodes;

        for (var i = 0; i < childNodes.length; i++) {
          document.write(childNodes[i].localName);
          document.write("<br>");
        }
    </script>

Upvotes: 1

Related Questions