Why don’t we just use element IDs as identifiers in JavaScript?

Anyway, this method seems to be quite poorly documented, and In fact, the sources I come across don’t even give it a mention […]

Reliance on implicitly-declared global variables aside, the lack of documentation is a great reason not to use it.

The apparent promotion of id values into global variables isn’t standards compliant (the HTML5 spec for the ID attribute doesn’t mention it) and, therefore, you shouldn’t assume future browsers will implement it.

EDIT: It turns out this behaviour is standards compliant – In HTML5, window should support property access to “Named Elements”:

Named objects with the name name, for the purposes of the above algorithm, are those that are either:

  • child browsing contexts of the active document whose name is name,
  • a, applet, area, embed, form, frameset, img, or object elements that have
    a name content attribute whose value is name, or
  • HTML elements that have an id content attribute whose value is name.

Source: HTML 5 spec, ‘Named access on window object”, emphasis mine.

Based on this, standards compliance is not a reason to avoid this pattern. However, the spec itself advises against its use:

As a general rule, relying on this will lead to brittle code. Which
IDs end up mapping to this API can vary over time, as new features are
added to the Web platform, for example. Instead of this, use
document.getElementById() or document.querySelector().

Leave a Comment