I knew in js I can select this -> <div id='x'>xd</div>
element via document.getElementById('x')
or document.querySelector('#x')
, but today I discovered I can just select it writing x
like it's a variable in my script already. The question is what is this method called and what is browser support?
Asked
Active
Viewed 32 times
0

Karol Kołodziejczyk
- 51
- 4
-
3Does this answer your question? [Do DOM tree elements with ids become global variables?](https://stackoverflow.com/questions/3434278/do-dom-tree-elements-with-ids-become-global-variables) – takendarkk Feb 17 '21 at 15:53
-
Yes, thanks a lot. – Karol Kołodziejczyk Feb 17 '21 at 17:05
1 Answers
0
Hah TIL: it turns out it is part of the HTML specifications
I would recommend to avoid using that feature, that could cause a lot of confusion and waste of time on a bug that is actually a feature.
Say you have declared x and given it a value, it makes it virtually impossible to retrieve the element with id x
and use your own separate variable x
with more likely a different meaning.

axelduch
- 10,769
- 2
- 31
- 50