Domanda

I think "document.documentElement.cildNodes" is all childnodes in tag as before,but today I do my code excrise, I find a special case:

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

why I excute "document.documentElement.childNodes" in tag and function in tag will get different result? I hope someone can give me more exsample about this.Thank you very much!

È stato utile?

Soluzione

The point is, you do it in a head script tag so when it gets executed, the whole DOM hasn't been loaded in the page, yet. And when you call the function for instance in the console, the DOM is loaded completely, to make sure of that you can move all your code to a window.onload event, like this:

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);
});

and if you don't want to use window.onload event, simply put it inside your body tag:

<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>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top