Javascript: Why get an element with getElementById(id) when it is still present in js? [duplicate]

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?

Answers:

Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.