Skip to main content

HTML id as a global variable

Learning something new every day, huh?


Today I learned that browsers add HTML elements with an id or name attribute to the window object. As a result, they become global variables in JavaScript. Take this example:

<div id="hello"></div>
<script>
  console.log(hello)
</script>

// Output: <div id="hello"></div>

I found a StackOverflow article from 12 years back asking about this behaviour. It turns out these global variables are named elements, while the feature is known as Named access on the window object. Internet Explorer introduced this functionality, and later, other browsers adopted it as some websites relied on the behaviour. Fascinating!

My first thought was: "Oh, why hasn't this behaviour ever clashed with any of my JavaScript code?" The answer is simple: If you declare a variable with the same name, it will precede the global variable:

<div id="hello"></div>
<script>
  const hello = "Something else"
  console.log(hello)
</script>

// Output: "Something else"

It's also discouraged to use id or name tags to access the DOM. Instead, with vanilla JavaScript, use querySelector or getElementById methods.

Live and learn!

Get in touch

I'm not currently looking for freelancer work, but if you want to have a chat, feel free to contact me.

Contact