It’s part of an obscure feature in the HTML5 spec called “Named access on the
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
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.