3

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.

  • 1
    This is a *bad idea* to rely on, as a global variable named `h` will shadow this property and effectively hide it. – Jeremy J Starcher May 14 '16 at 07:57
  • 1
    See also [Do DOM tree elements with ids become global variables?](http://stackoverflow.com/questions/3434278/do-dom-tree-elements-with-ids-become-global-variables). AFAIK it has become standadized. – traktor May 14 '16 at 08:06

3 Answers3

9

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.

gurvinder372
  • 66,980
  • 10
  • 72
  • 94
2

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.

Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
1

To demonstrate the above answers practically...

Html:

<div id="foo">
  <p>bar</p>
</div>

Javascript:

alert(window.foo);
console.log(window.foo.innerHTML);

Alert:

[object HTMLDivElement]

Console:

<p>bar</p>
TeamRad
  • 89
  • 5