2024-01-15

window variable for HTML id

But let's go back to more obscure trivia.

Any HTML element with an id attribute automatically gets a variable in the global scope. Then it can be accessed through the window object or even by its name.

HTML:

<div id="foo"></div>

JavaScript:

console.log(window.foo); // prints the element above
console.log(foo);        // same, if the variable hasn't been shadowed

What about ids with dashes in it, something allowed in HTML? This is where JavaScript says enough and doesn't translate foo-bar to fooBar (which kind of feels intuitive; that's how element.style.paddingTop works, for instance). That's a downside because we need to use the dictionary access (window['foo-bar']) and no variable is available.

It also respects existing props. So creating divs with id of either Array or crypto won't work. The prop/var can be also easily overwritten by creating a global variable with matching name, hence, it's a rather bad idea to use it.

But it's there since JavaScript inception and probably will stay forever, just in case someone used it back in 1997 in their codebase.