Categories
Posts

IDs in Window

When you assign a DOM element an ID, that ID becomes part of the window object. No joke, in the spec even ( emphasis mine ):

7.2.4 Named access on the Window object

The Window interface supports named properties. The supported property names at any moment consist of the following, in tree order, ignoring later duplicates:

the value of the id content attribute of any HTML element in the active document with a non-empty id content attribute.

On josephscott.org the sidebar section has an ID of “sidebar”, which is easily accessed in the Chrome Console:

global-ids-dom

I’d recommend never doing this in real code ( great for quick debugging in the JavaScript console though ). Instead stick with document.getElementById( 'thingid' );, which is significantly faster.

2 replies on “IDs in Window”

What is it that you don’t recommend? using ids at all or just window.?
Because, if you just use ids, they *will* be defined in the window scope, whether you use them or not!

I don’t recommend using window.someid or someid in regular code. From what I’ve seen ( the link to jsperf in the post ) using document.getElementById( 'someid' ); is significantly faster.

Leave a Reply

Your email address will not be published. Required fields are marked *