javascripthtmldomdom-node

What is the "text" child node of the html node?


I have tried to search but have not found an answer to this:

So I know that when a page is passed to or downloaded by a browser a tree structure representation of the page, called the DOM, is generated. Javascript can then be used to manipulate the nodes (objects representing elements) of this tree.

So now if I open Chrome's developer console and execute the command:

document.childNodes;

I get what I expect, namely two nodes which are the DOCTYPE and the html nodes

[<!DOCTYPE html>, html]

If I now assign a variable to the html and then check it's nodes like so:

var htmlNode = document.childNodes[1];
htmlNode.childNodes;

Something weird happens:

I get the "head" node as expected, and then there is a "text" node which I have no idea where it's coming from, then finally the "body" node as expected.

[head, text, body]

My question is where is this "text" node coming from?

enter image description here


Solution

  • Although HTML says that the html element can only normally contain head and body, inter-element whitespace is of course allowed between any of these elements' start and end tags.

    In the HTML DOM, inter-element whitespace is always distributed into text nodes. So, presumably, the text node you're seeing between the head and body element nodes is the inter-element whitespace between the </head> end tag and the <body> start tag.