javascript为什么“document.documentElement.childNodes”输出不同的结果?

时间:2014-02-17 09:03:51

标签: javascript dom document

我认为“document.documentElement.cildNodes”就像以前一样是标签中的所有子节点,但今天我做了我的代码,我发现了一个特例:

<!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>

为什么我在标签中执行“document.documentElement.childNodes”并且标签中的函数会得到不同的结果? 我希望有人可以给我更多关于此的例子。非常感谢你!

1 个答案:

答案 0 :(得分:3)

关键是,你是在头部脚本标签中执行它,所以当它被执行时,整个DOM还没有被加载到页面中。当您在控制台中调用该函数时,DOM会完全加载,以确保您可以将所有代码移动到 window.onload 事件,如下所示:

window.addEventListener("load", function () {
    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 not 1
    alert(ohtml.childNodes.length); // not just head
    ohtml.childNodes[0].appendChild(o);
});

如果您不想使用 window.onload 事件,只需将其放在身体标记内:

<body>
<!--your stuff-->
<script>
    alert(ohtml.nodeName); //output HTML
    alert(ohtml.childNodes.length); //nodes length is not 1
    alert(ohtml.childNodes.length); // not just head
</script>
</body>