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

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.

Leave a Comment