Why Does it Work? - getElementById

Hi Guys,

Ive stumbled on this phenomenon and it is confusing me a little, Ive added a link to my JS Scribble.

So in essence what I’ve found is if I have a div with and id of “test” that I want to manipulate with getElementById (test.getElementById) I do not need to set a "var test = document.getElementById(“test”); ", JavaScript seems to know intuitively that the “test” in test.getElementById is the id=“test” in the HTML?

But as soon as I want to use a different variable name like x.getElementById, then I need to do the var x = document.getElementById(“test”); which is understandable.

I find it strange that JavaScript is just assuming that the var name I’m using is referring to the id in the HTML?

Is this a new update, an old bug?


Every DOM element with an ID gets a global variable - this is expected behavior according to the HTML standard - support may vary across browsers like any HTML or JS feature


So this <div> element in HTML

<div id=div0></div>

is available in chrome as div0 in javascript

div0.tagName // "DIV"
div0.outerHTML // "<div id="id0"></div>"

btw getElementById is a function and it is only present for document not other DOM elements - test.getElementById is undefined