[whatwg] [WHATWG] HTMLElement ids as global object properties

Jukka K. Korpela jkorpela at cs.tut.fi
Fri Apr 1 01:24:55 PDT 2011

Alexandre Morgaut wrote:

> My biggest nightmare today is that recent browsers like Chrome, IE9,
> FF4 generate a global variable from the id of each HTMLElement of the
> document...

On a day like this, I was very suspicious about information like that, but 
it turns out to be true and also applies to Opera and Safari.

Using <h1 id="foo">Hello world</h1> in markup and alert(foo.innerHTML) I get 
"Hello world" instead of an error message. On the other hand, if I declare 
var foo, I don't get an error message about duplicate declaration.

> Let's imagine the effects of existing HTMLElements with id like
> "location", "document", "event", "toolbar", or even "window"...

Using "location" instead of "foo", I get "undefined". Ditto if I declare a 
function with that name, before _or after_ the reference to foo.

So the automagic generation of variables corresponding to id attribute 
values does not extend to names that are already defined.

But it's not that simple:

var foo;

causes the error message "foo is undefined".

Is there something about this in some document on HTML(5)?

Technically this might be regarded as JavaScript error handling (treating an 
undefined identifier as referring to an HTMLElement with that id) that is 
outside the scope of any HTML specs. But in practice it looks far too 
important to be ignored, especially since the browser behavior is so 

When I test the simple case (no defined name clashing with the id value) on 
Firefox with Firebug enabled, I get a _warning_ from Firebug, saying that an 
element was referred to using an ID/NAME and that the W3C-conforming 
document.getElementById() request should be used instead. So this seems to 
be a known issue to some extent.

Yucca, http://www.cs.tut.fi/~jkorpela/ 

More information about the whatwg mailing list