Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
61
rated 0 times [  66] [ 5]  / answers: 1 / hits: 29880  / 12 Years ago, sat, october 20, 2012, 12:00:00

I write the following JS and run in IE 10:



function test() {
var nodes = document.getElementsByTagName(h1);
document.writeln(nodes.length);
for (var j = 0; j < nodes.length; j++) { <=== THIS LINE!
document.writeln(j.toString());
}
document.writeln(abc);
}


But I kept get invalid calling object error for the marked line.



Why?



And here is my page source:



<!DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Transitional//EN http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd>
<html xmlns=http://www.w3.org/1999/xhtml >
<head>
<title>This is JS fun!</title>
<script type=text/javascript language=javascript src=test.js>
</script>
</head>
<body>
<h1>1111</h1>
<h1>2222</h1>
<h1>3333</h1>
<h1>4444</h1>
<input type=button onclick=test() value=click me! />
</body>
</html>


Below is my screenshot:



enter


More From » javascript

 Answers
131

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/


[#82460] Thursday, October 18, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sabinal

Total Points: 144
Total Questions: 112
Total Answers: 107

Location: Ghana
Member since Mon, Aug 22, 2022
2 Years ago
;