DEV Community

JS Bits Bill
JS Bits Bill

Posted on • Edited on

4 1

JS Quirk: Element IDs are global variables!

Here's an interesting quirk I recently discovered:

Any HTML element containing an id creates a global variable of the same name.

Let's start with our HTML:

<html>
  <head></head>
  <body>
    <h1 id="title">Hello World</h1>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

This is what we'll see in the console when we reference window.title:

There's some interesting behavior with this though. You can overwrite this variable as you'd expect:

But let's say we deleted our <h1> element and added another with the same id. Would this overwrite the global variable again?

It does not! 😮

That's probably a good thing since this would probably cause many a confused developer!

Although I couldn't locate the documentation for this quirk in the DOM specification, this behavior appears consistent across Chrome, Firefox, Edge, and Safari. Interesting!


Check out more #JSBits at my blog, jsbits-yo.com. Or follow me on Twitter!

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay