Skip to main content Accessibility Feedback

Your browser automatically creates JavaScript variables for elements with an ID

One of my readers tipped me off to a really cool trick: your browser automatically creates JavaScript variables for any element with a unique ID.

It’s part of an obscure feature in the HTML5 spec called “Named access on the Window object.”

How it works #

<div id="example">Here's an example. Open up developer tools and try it yourself.</div>
// Automatically logs `<div id="example">`
console.log(example);

Here’s an example. Open up developers tools and try it yourself.

That’s great for element’s with one-word and camel-case IDs, but what about something like this?

<div id="another-example">Here's another example. Will it work?</div>

Here’s another example. Will it work?

You can’t just call another-example in the console, because that’s not a valid JavaScript variable. You’ll get this.

console.log(another-example);
// Uncaught ReferenceError: another is not defined

Turns out, the browser attaches these to the window, and you can reference them as a property.

// Logs `<div id="another-example">`
console.log(window['another-example']);

When should you use this? #

Never, ever, ever, ever in your actual code base.

This is great for doing quick debugging without having to use querySelector() to look things up, but you should never rely on it in production code. It’s too easy to overwrite these.


🚀 Make 2018 the year you master JavaScript! My pocket guides and mini courses are short, focused, and made for beginners. You can do this!

Have any questions or comments about this post? Email me at chris@gomakethings.com or contact me on Twitter at @ChrisFerdinandi.

Get Daily Developer Tips