W3C home > Mailing lists > Public > whatwg@whatwg.org > April 2011

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

From: Jukka K. Korpela <jkorpela@cs.tut.fi>
Date: Fri, 1 Apr 2011 11:24:55 +0300
Message-ID: <C40C058ECD9048DBA67AD1AF0B400E66@JukanPC>
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:

alert(foo.innerHTML);
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 
consistent.

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/ 
Received on Friday, 1 April 2011 01:24:55 GMT

This archive was generated by hypermail 2.2.0+W3C-0.50 : Wednesday, 30 January 2013 18:48:03 GMT