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 name
s, 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.