DEV Community

Discussion on: DOM elements with ID's are global variables

Collapse
 
loderunner profile image
Charles Francoise

Nicely spotted! Although we're supposed to think of "global" variables as Bad™, I think there's a definite case to be made why this is actually Not So Bad™.

An DOM element with an ID, by definition, can be referenced from any context. Semantically, it is pretty akin to a "global variable". Also, one of the guarantees of DOM elements with IDs is that they have a speedy lookup (O(1) if possible).

With these assumptions, it makes sense that a naive implementation would store them somewhere in the global scope. Would it have been better to store them in a member object, such as window.elementsWithIds? Probably, but quite marginally. And as Rachel Carvalho pointed out, not necessarily worth breaking legacy applications.

Great catch, though. I think all front-end developers should be aware of this, if only to avoid mind-bending bugs like the one you mentioned and to understand the inner workings of the target machine (aka "The Browser").

--

EDIT: I'm quite new at Javascript so I'm bound to make some errors.

My previous argument doesn't hold in face of this little snippet.

<html>
<body>
<div id="crypto">Crypto</div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode
> document.getElementById('crypto')
<div id=​"crypto">​Crypto​</div>​

> window.crypto
Crypto {subtle: SubtleCrypto}
Enter fullscreen mode Exit fullscreen mode

Naming your element after a built-in Window property does not overwrite the property, but you can still perform a lookup by ID on the document. So there's obviously a better mechanism already in place.

The fact that IDs create global objects is probably only to maintain backwards compatibility, as Rachel pointed out.

Collapse
 
stephenhand profile image
Stephen Hand

Dom elements referenced by ID are global variables and have the same drawbacks as other global variables. I've seen more than supposedly 'reuseable component' break as soon as you tried to add a second instance of it to a page because it's referencing its internal DOM elements by ID...