Foo
window.foo returns the dom ele...">

Why do dom elements exist as properties on a window object?

If I write html as follows:

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

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

Why? And why does everyone use getElementById ?

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

+7
javascript dom html
source share
3 answers

I'm not sure about the historical perspective, but HTML 5 indicates that the elements are candidates that will be directly exposed as properties in the window object, if they have an id attribute:

The Window interface supports named properties. Supported property names at any time 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 <div id="foo">Foo<div> exists then window.foo will be defined. This does not guarantee what exactly its value will be (read the specification for the rules on how this is defined, for example, it can return a collection ).

So, the answer to the question "why use getElementById ever?" simple: because you can depend on it to return what you expect without taking into account the entire document.

+4
source share

In general, placing something inside a window object will make it global. For example:

 var A = function() { window.test = "bla"; console.log(test); } var B = function() { console.log(test); } A(); B(); 

However, this is not a good practice. You should not rely on any global object, because you can move your code to a browser that does not have a window. Or, for example, for nodejs.

I find window.foo a bit wrong because you may have code that creates the global variable foo. Thus, using getElementById ensures that you always get a DOM element.

0
source share

Window.foo works fine in your scenario, but what if Id is something like this "foo-test" instead of "foo", you can see that it won't work. this is because Javascript variables are not allowed for dashes in it .... While it will work fine in the case of document.getElementById

0
source share

All Articles