2

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Z.H.
  • 259
  • 1
  • 14

2 Answers2

4

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.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • @Šime: I didn't say only IE ;) Chrome does it to be compatible afaik, but imo that's just silly. – Felix Kling Apr 15 '12 at 11:37
  • This is specified by the HTML standard btw. – Šime Vidas Apr 15 '12 at 11:40
  • It's here: http://www.whatwg.org/specs/web-apps/current-work/#named-access-on-the-window-object – Šime Vidas Apr 15 '12 at 11:42
  • Mmh. It seems that WHATWG is different than W3C... difficult to say what is "official" (I actually have no clue about the relationships of these groups). In any case, there seem to be problems with it: https://www.w3.org/Bugs/Public/show_bug.cgi?id=11960, and the behviour is likely to change so I would not call this standard and I don't think it is in HTML4 (HTML5 is not officially released yet ;)) – Felix Kling Apr 15 '12 at 11:49
  • 1
    It's also in W3C's HTML5 standard - [see here](http://www.w3.org/TR/html5/browsers.html#named-access-on-the-window-object). That being said, it's a bad part of the standard and I hope the browser vendors will remove it from their browsers eventually. – Šime Vidas Apr 15 '12 at 11:57
  • Thanks for all the links! I honestly didn't know it was added to the HTML5 standard. I agree, it's a very dubious feature and will probably cause more problems than it solves. – Felix Kling Apr 15 '12 at 12:03
3

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 .

Maxim Krizhanovsky
  • 26,265
  • 5
  • 59
  • 89