Is getElementById optional in some browsers?

When accessing elements using window.someThing, "someThing" should be the name of the html element. But now I see that I can access the element by id in the same way, without document.getElementById. When was this changed? It seems to work in Chrome, IE, Firefox 13, but not in Firefox 12.

For example:

<div id="MyDiv">Content</div> <script> MyDiv.innerHTML = "New Content"; </script> 

Why does the above example work? Why I should not do:

 var MyDiv = document.getElementById('MyDiv'); 

Is this something new, or was it always possible, and I just did not know about it?

+8
javascript html
source share
4 answers

http://www.quirksmode.org/dom/w3c_core.html#gettingelements
It was (mostly) implemented with IE 5.5

I can not find any information about using the identifier as a variable name. I recommend sticking with getElementById("MyDiv").doSomething instead of MyDiv.doSomething to improve compatibility. Especially when you write large scripts, you can mix variable names with the identifier used on the page. getElementById ensures that you "get" the DOM element.

+4
source share

This is not standard JavaScript behavior. When adding a variable, as in the case of var MyDiv , the variable was added to the window object so that it could be accessed directly, as if it were a property, but DOM elements were never added. I personally do not know the reasons for the new behavior, but I assume that this is simply an extension of the language engine. If you really want to know what the behavior is, you can always read the standard: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf

Edit: Also note that the method that is used to get the element is document.getElementById() , which comes from the document's object model. The method you are referring to is placing the id in the window object, which can create conflicts by id. The standard method is to get an element from document and not put things in a window . Using a window object this way will be similar to using a global variable (which is bad practice re: http://www.javascripttoolbox.com/bestpractices/#namespace )

+1
source share

AVOID IT!

This seems like an awesome feature, but I would recommend not using it, because if you have a div with an identifier similar to that of some global JS variables, this will be inconsistent, and also ruin the stuff in some other third-party JS files which you turned on.

But you always have a jQuery selector always with you and don't forget the new querySelector function in modern browsers :)

+1
source share

You can find your answer here: Can I use an identifier as a variable name?

In short, avoid this.

The reason this works is because the browser actually creates the variable window.document.myDiv

+1
source share

All Articles