Referring from JavaScript The Definitive Guide:
If you name an element in your HTML document using the id attribute, and if the
Window object does not already have a property by that name, the Window object is
given a nonenumerable property whose name is the value of the id
attribute and whose name is the HTMLElement object that represents that document element.
Window object serves as the global object at the top of the scope chain in client-side JavaScript, so this means that the id attributes you use in your HTML documents become global variables accessible to your scripts. If your document includes the element <button id="okay"/>
, you can refer to that element using the global variable okay
.
But there are certain exceptions as well. If window
object has already a property with a name that is also used as an id
attribute in html document it will not be available as property on window object.
Second if you have an id which is available as window property and we declare a variable with same name as well, then our explicitly created variable will override that window property containing id.