Z.H.
Z.H.

Reputation: 259

getElementById issue in IE?

Why the following code runs well in Firefox and Chrome but causes an error in IE6 and IE8?

<!DOCTYPE html>
<html>  
<head></head>  
<body>
<div id="abc"></div>
<script type="text/javascript">
var doLoad = function() {
  // error in ie6 and ie8
  abc = document.getElementById("abc"); 
  abc.innerHTML = "hello world!"; 
  // correct in ie6 and ie8
  /*
  var abc = document.getElementById("abc"); 
  abc.innerHTML = "hello world!";
  */
  // correct in ie6 and ie8
  /* 
  xyz = document.getElementById("abc"); 
  xyz.innerHTML = "hello world!";
  */
}
window.onload = doLoad;
</script>  
</body>  
</html>

But if I add var before document.getElementById("abc"); or rename abc as xyz, It would runs well in IE6 and IE8.

Upvotes: 2

Views: 860

Answers (2)

Maxim Krizhanovsky
Maxim Krizhanovsky

Reputation: 26739

When you miss the var statement, it assings the variable to window object. So it's the same as window.abc = document.getElementById('abc');

But window.abc is exactly the div with id abc and in IE you cannot assign value to it .

Upvotes: 3

Felix Kling
Felix Kling

Reputation: 817128

IE creates a global JavaScript variable for each element with an ID. These variables cannot be overridden afaik and cause all sorts of problems.

The thing to keep in mind: Don't create global variables with the same name as element IDs. Don't create global variables at all.

Upvotes: 4

Related Questions