While working on my code exercise today, I came across a special case regarding the "document.documentElement.childNodes" property. Originally, I believed it to represent all child nodes within a tag as before. However, when implementing my code, I noticed a discrepancy:
<!DOCTYPE html>
<html>
<head>
<title>javascript</title>
<script>
var o = document.createElement('script');
o.text = 'alert("111")';
var ohtml = document.documentElement;
alert(ohtml.nodeName); //output HTML
alert(ohtml.childNodes.length); //nodes length is 1
alert(ohtml.childNodes.length); //just head
ohtml.childNodes[0].appendChild(o);
function shownode() {
var ohtml = document.documentElement;
alert(ohtml.nodeName);
alert(ohtml.childNodes.length); //nodes length is 3
alert(ohtml.childNodes[0].nodeName); //head
alert(ohtml.childNodes[1].nodeName); //#text
alert(ohtml.childNodes[2].nodeName); //body
}
</script>
</head>
<body><div>test</div><input id="Button1" type="button" value="show nodes" onclick="shownode();" />
</body>
</html>
I am puzzled by the fact that executing "document.documentElement.childNodes" in a tag and within a function yields different results. Can anyone provide more examples or insights on this topic? Thank you!