3

Lately i noticed that a reference to a html element with an id can be accessed by javascript simply with a variable named like that id (jsbin).

why is this so? why do we have to even use getElementById(id) instead of simply writing id?

Hans Spieß
  • 897
  • 7
  • 13
  • 1
    Duplicate of a couple of questions, e.g. [Do DOM tree elements with ids become global variables?](http://stackoverflow.com/q/3434278/218196) and [Why don't we just use element IDs as identifiers in JavaScript?](http://stackoverflow.com/q/25325221/218196) – Felix Kling Dec 10 '16 at 17:08
  • @FelixKling: Good find. – T.J. Crowder Dec 11 '16 at 19:03

1 Answers1

6

why is this so?

Because early browsers did that, and it's now become standardized.

why do we have to even use getElementById(id) instead of simply writing id?

Technically, you don't. But beware that the global namespace is really, really crowded. There's a whole bunch of stuff thrown in there. Not just elements with IDs, but certain elements if they have names, the browser context by name, etc., etc., which means there can be conflicts. For instance, if you had an element with id="document", the automatic global won't be created. The other, conflicting globals can vary by browser. Also, id values that aren't valid JavaScript identifiers (like id="foo-bar") are still perfectly valid id values, but the automatic global for it (window["foo-bar"]) is awkward to use.

Using getElementById specifically looks for an element with that ID1 (not name, etc.). So it's more contained and reliable.


1 Ignoring bugs in obsolete versions of IE, which failed to constrain it correctly.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875