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?
If you list only the objects instead of their
localNameyou will see:So you receive
nullfor thelocalNameof the text node. To fix this you needchildreninstead ofchildNodes:Here is demo in JSFiddle.