Reputation: 74520
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:
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.
Upvotes: 1
Views: 127
Reputation: 875
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.
Upvotes: 1