Why is this “invalid calling object” error?

前端 未结 3 1637
执笔经年
执笔经年 2020-12-30 02:57

I write the following JS and run in IE 10:

function test() {
    var nodes = document.getElementsByTagName(\"h1\");
    document.writeln(nodes.length);
    f         


        
相关标签:
3条回答
  • 2020-12-30 03:25

    The error comes because you are running the code after the page is completed.

    The first document.writeln call creates a new document with only the string in it. That means that the collection in nodes is no longer valid. It is a collection of elements in a document that doesn't exist any more, so you can't use any of the properties (like length) of the collection any more.

    If you run the code while the page is being created, it works fine: http://jsfiddle.net/Guffa/4w949/

    0 讨论(0)
  • 2020-12-30 03:31

    j is a variable counter, not the object.

    You need nodes.item(j).toString();

    0 讨论(0)
  • 2020-12-30 03:33

    OK, I may have figured it out.

    I tried this:

    function test() {
        var nodes = document.getElementsByTagName("h1");
        document.writeln(nodes.length); // 1st writeln
        nodes2 = document.getElementsByTagName("h1");
        alert(nodes2.length);  //  <========= MARK1
        for (var j = 0; j < nodes2.length; j++) {
            alert(j);
                }
        document.writeln("abc");
    }
    

    No error for above code. but the MARK1 line gives 0. Because after the 1st writeln, the complete page content is re-constructed, there's no < h1 > tag in the newly constructed page any more.

    And then I changed the above code to this:

     function test() {
        var nodes = document.getElementsByTagName("h1");
        document.writeln(nodes.length + "<h1>new h1</h1>");   // ADD a new < h1 > tag
        nodes2 = document.getElementsByTagName("h1");
        alert("node2 length = " + nodes2.length);   //MARKED
        for (var j = 0; j < nodes2.length; j++) {
            alert(j);
                }
        document.writeln("abc");
    }
    

    Now the MARKED line gave me expected length, 1. Because I put a new < h1 > tag into the newly constructed document.

    As to the Invalid Calling Object error. I think because the document is re-constructed with writeln, all the DOM objects previously obtained with the old invalidated document object will be invalided, too.

    The key is the implicit creation of a new document by document.writeln method.

    Please correct me if I am wrong.

    Thanks Guffa for the insight.

    0 讨论(0)
提交回复
热议问题