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 thandocument.getElementByID
.
Here is a demo.
*I've tested this in the latest versions of Chrome, Firefox, and IE.