IE is the only browser that behaves as you would expect. All other browsers implement the standard and the standard says that whitespace must also be part of the DOM.
Therefore, for HTML that looks like this:
<html>
<body>
<div>Hello</div>
</body>
</html>
IE will create this DOM:
html +
|____ body +
|____ div +
|____ text("Hello")
But all other browsers will create this DOM
html +
|____ text("\n ")
|
|____ body +
| |____ text("\n ")
| |
| |____ div +
| | |____ text("Hello")
| |
| |____ text("\n ")
|
|____ text("\n ")
I'm not sure how you got your result because there should be text nodes before and after <html>
.
Anyway, the answer is because the standard requires it. So don't blindly use hardcoded index to traverse childNodes because things like minifiers may change the DOM due to whitespace. Either loop through all children and stop once you find the node you want or use getElementsByTagName.