Web_Designer
Web_Designer

Reputation: 74520

Accessing elements with IDs via their global variables

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:


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

Upvotes: 1

Views: 127

Answers (2)

louisbros
louisbros

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

Xotic750
Xotic750

Reputation: 23472

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

Upvotes: 2

Related Questions