Vishal Subramanyam Rajesh Vishal Subramanyam Rajesh - 6 months ago 17
HTML Question

Accessing a div using id without getElementById and jQuery

I believe that the standard way in JS to access an element with an id is by using getElementById. If people like to use jQuery, then they probably will use their selectors. But recently I came across a very simple code example which is below:

HTML:

<div id="h">Hello</div>


JS:

h.innerHTML = "Too bad";


This is the only code and there are no other variable declarations, just for people to know.

How are we able to access the div element as if it is a Javascript object?

P.S. : The code example works.

Answer

How are we able to access the div element as if it is a Javascript object?

ids are created by default as properties of global object (in global context).

if you do <div id="h22">Hello</div> it will create a global variable of h22

As per spec,

Otherwise return an HTMLCollection rooted at the Document node, whose filter matches only named objects with the name name. (By definition, these will all be elements.)

HTML elements that have an id content attribute whose value is name.

So the window can determine in the order given in the spec where to pick the value from.