Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do dom-elements exist as properties on the window-object? [duplicate]

If I write html like this:

<div id="foo">Foo<div>

window.foo returns a dom-element and window.document.getElementById("foo") === window.foo returns true.

Why is that? And why does everyone use getElementById?

And on a sidenote: Why was overriding window.foo forbidden in IE7/8? And what happens if I set window.foo = "bar"?

like image 380
Nils Avatar asked Sep 10 '13 07:09

Nils


People also ask

What are the properties of DOM in JavaScript?

In the DOM, all HTML elements are defined as objects. The programming interface is the properties and methods of each object. A property is a value that you can get or set (like changing the content of an HTML element). A method is an action you can do (like add or deleting an HTML element).

Is the window object part of the DOM?

Output: Window Object: The window object is the topmost object of the DOM hierarchy. It represents a browser window or frame that displays the contents of the webpage.

What is DOM and window object?

The Window interface represents a window containing a DOM document; the document property points to the DOM document loaded in that window. A window for a given document can be obtained using the document. defaultView property.


1 Answers

I am not sure about the historical perspective, but HTML 5 specifies that elements are candidates to be directly exposed as properties on the window object if they have an id attribute:

The Window interface supports named properties. The supported property names at any moment consist of the following, in tree order, ignoring later duplicates:

[...]

  • the value of the id content attribute of any HTML element in the active document with a non-empty id content attribute.

The problem with this definition is that it only guarantees that if there is a <div id="foo">Foo<div> then window.foo will be defined. It does not guarantee what exactly its value will be (read the spec for the rules on how that is determined; for example, it might return a collection).

So it turns out the answer to "why use getElementById ever?" is simple: because you can depend on it to return what you expect without needing to take into account the whole document.

like image 50
Jon Avatar answered Sep 20 '22 09:09

Jon