1

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?

  • 1
    possible duplicate of [What are the drawbacks of accessing DOM elements directly by ID?](http://stackoverflow.com/questions/1097250/what-are-the-drawbacks-of-accessing-dom-elements-directly-by-id), *related* (reading is highly recommended): [IE/Chrome: are DOM tree elements global variables here?](http://stackoverflow.com/questions/3434278/ie-chrome-are-dom-tree-elements-global-variables-here) – Felix Kling Aug 24 '11 at 00:48
  • I think you should check this http://stackoverflow.com/questions/3434278/ie-chrome-are-dom-tree-elements-global-variables-here (lots of helpful info) – Pantelis Aug 24 '11 at 00:49
  • Thanks, guys. I could not find those questions for the life of me. I need to work on my Google-fu... – Richard Lee Aug 24 '11 at 01:21

2 Answers2

1

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.

RobG
  • 142,382
  • 31
  • 172
  • 209
0

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

http://jsfiddle.net/rrSwW/

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189