Named access on the window object

Originally published at kbarker.dev on Sep 28, 2020

Imagine an HTML element with the ID #app. You might be used to selecting said element with the querySelector() or getElementById() methods. But did you know that it’s possible to access the element as a property of the window object—like window.app, or just app? Yeah, this is cool and everything, but I’m here to talk you out of it.

There’s a section about this in the HTML specification called Named access on the Window objectRight at the top, they advise against it:

As a general rule, relying on this will lead to brittle code. Which IDs end up mapping to this API can vary over time, as new features are added to the web platform, for example. Instead of this, use document.getElementById() or document.querySelector().

There’s also a good answer on StackOverflow about why you shouldn’t do this.

I’m not going to go into detail myself because it’s quite complicated and long-winded. I just want to make you aware of this behaviour in case you see it in the wild and wonder what the heck is going on.

Stick to the querySelector() and getElementById() methods.

If you have questions, feedback, or any other suggestions, please do leave a comment. I'd love to hear from you!

I made a YouTube video to go with this post, if you’re interested.

Interesting, stuff like this should be removed if it's considered bad eh I guess it had a use at some point...

Like
Reply

To view or add a comment, sign in

More articles by Kieran Barker

  • The const keyword in JavaScript

    Originally published at kbarker.dev on Oct 12, 2020 Traditionally, we always declared variables in JavaScript using the…

  • Implicit return statements in JavaScript

    Originally published at kbarker.dev on Oct 05, 2020 Back in May, I wrote about three ways to write a function in…

Explore content categories