Why is this “invalid calling object” error?

前端 未结 3 1648
执笔经年
执笔经年 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/

提交回复
热议问题