Saturday 14 October 2017

javascript - Cannot understand why the html tag does not have both head and body as child nodes?

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



HTML:



            html>
lang="en">



charset="utf-8">



DOM<br /> Traversing







  1. href="">One

    • href="">1.1

    • href="">1.2

    • href="">1.3




  2. Two


  3. Three



  4. Four








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:



href="https://i.stack.imgur.com/ybGBg.png" rel="nofollow noreferrer"> src="https://i.stack.imgur.com/ybGBg.png" alt="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.

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...