Is there a spec that the id of elements should be made global variable?

Name picture Name · Jun 17, 2011 · Viewed 9.8k times · Source

If I have a <div id='a'> in Chrome then in javascript I can do a.stuff() (it's like as if a is a global variable).

However this does not work with FireFox - I will need to use document.getElementById('a').

What is the correct behaviour here? (according to W3 specs that is)

Also I'm interested in how will Chrome resolve the ambiguity if I have a div with id a yet have a global variable called a too in my script. Is the behavior going to be random and whacky?

And how would an element with id consisting of hyphens ("-"), colons (":"), and periods (".") be translated (ok i know they can be accessed with document.getElementById but how will the browser translate it into the global variable that was representing them)

Answer

Niall Smart picture Niall Smart · Jun 17, 2011

It depends on which spec you read. :)

This behavior is not described by the HTML4 specification (c.f., http://www.w3.org/TR/1999/REC-html401-19991224/struct/global.html#adef-id and http://www.w3.org/TR/1999/REC-html401-19991224/types.html#type-name). However, it was introduced by Internet Explorer and then copied in other major browsers for compatibility. FireFox also displays this behavior, but only in quirks mode (and even then its implementation seems buggy).

The WHATWG HTML spec currently requires this behavior (a bug report requesting it be removed was closed WONTFIX).

Regardless of spec compliance, using the global namespace (i.e., window) for application code is generally considered bad behavior. Consider referencing element IDs using document.getElementById() or jQuery convenience methods (e.g., $("#a")) and using function-scoped variables to avoid introducing new variables into the global namespace.

There is a longer discussion of this behavior on the WHATWG mailing list.