1

It is a not-so-widely-known fact that most* web browsers create a global variable for every element on a page with an id attribute:

HTML:

<header id="page-header"></header>


JS:

window['page-header'].style.fontFamily = "Comic Sans MS";


My Questions:

  • Is this a reliable way to select elements?
  • Any reason to use document.getElementByID instead? I would guess that accessing ID'd elements with their global variables would be faster than document.getElementByID.


Here is a demo.
*I've tested this in the latest versions of Chrome, Firefox, and IE.

Rashwan L
  • 38,237
  • 7
  • 103
  • 107
Web_Designer
  • 72,308
  • 93
  • 206
  • 262
  • Please don't downvote just because this is bad practice. I'm asking *why* it's bad practice. – Web_Designer Apr 17 '13 at 23:35
  • Found an informative duplicate. Sorry for the bother: [IE/Chrome: are DOM tree elements global variables here?](http://stackoverflow.com/questions/3434278/ie-chrome-are-dom-tree-elements-global-variables-here) – Web_Designer Apr 17 '13 at 23:51

2 Answers2

2

I tested it on jsperf and with Chromium v25 getElementByID was much faster

Xotic750
  • 22,914
  • 8
  • 57
  • 79
1

Some things to consider:

If the window object already has a property with that name it won't be overwritten.

Elements like img that use the name attribute will also become properties of the window object. Since the name attribute is not required to be unique, this could happen:

<img name="test"/>
<img name="test"/>
<img id="test"/>

In some older browsers window.test will return a NodeList containing the three elements.

So it is safer to use the getElementById method.

louisbros
  • 865
  • 5
  • 10