Richard Lee
Richard Lee

Reputation: 15

Referring to HTML elements in Javascript by just their ID

Apparently the ids for HTML elements get loaded into the global namespace for Javascript on an HTML page. As such, if I have HTML like:

<p id="mypara">Hello</p>

I can run Javascript like:

mypara.innerText += " world";

which results in the paragraph having "Hello world" as its text in IE9 and Chrome on Windows. This seems like a more convenient way to refer to HTML elements than the standard

document.getElementById("mypara").innerText += " world";

As far as I can tell, the cons seem to be that you can't give HTML elements ids that are Javascript keywords (doesn't seem so bad) and your global namespace is more polluted.

Are there any other problems with this approach? Is there any documentation that describes exactly when/how the population of the global namespace is done by browsers? Are there quirks or pitfalls? Has anyone done any browser compatibility testing?

Upvotes: 1

Views: 444

Answers (2)

RobG
RobG

Reputation: 147403

Early IE introduced the practice of making element ids and names global references to the elements. It was never standardised and was considered a very bad idea.

Other browsers provided various levels of support for the practice to be compatible with sites written for IE, but generally support was minimal (even hidden to some extent) to discourage its use. Some browsers only supported it in quirks mode or with certain DOCTYPEs.

It is still considered a very bad idea, do not use it. Use appropriate DOM methods, don't rely on such browser quirks.

Upvotes: 1

Kevin Bowersox
Kevin Bowersox

Reputation: 94469

I would worry about the script working in older browsers. For example this fiddle does not work in Firefox 3.

http://jsfiddle.net/rrSwW/

Upvotes: 0

Related Questions