Why use getElementById if the id is in the window?

54

Recently in my study I noticed an object that manipulated the DOM of the element that had the same name in its id .

teste.style.border = '1px solid #CCC';
teste.style.width = '500px';
teste.style.height = '50px';
<div id="teste">
</div>

Doubt

  • Why does ids go to global space ?
  • If I can access the element directly by its id , why use getElementById ?

Note

Composite name objects are accessible in window

window['teste-id_composto'].style.border = '1px solid #CCC';
window['teste-id_composto'].style.width = '500px';
window['teste-id_composto'].style.height = '50px';
<div id="teste-id_composto">
</div>
    
asked by anonymous 13.04.2016 / 14:23

3 answers

65

The fact that elements named * belong to the properties of document and / or window is unfortunate, due to very simple applications that were many years ago, at the beginning of the DOM and JavaScript.

Unfortunately for being used and some browsers promote them they still exist so as not to break old code, and are even common practice. Having references to elements in the properties of document or window is a very bad idea, since they occupy the same space as code variables of the applications that are run and can be "deleted". Yes, declaring a function or variable in the global space overrides any property that comes from a named element that uses the same name.

What is the safe solution to separate the water?

= > use document.getElementById() and / or document.querySelector()

What does W3C say?

The HTML 5.1 specification (April 12, 2016) is very clear here and recommends not accessing named elements, via document or window . In the spec says so :

  

As a general rule, relying on this will lead to brittle code. Which IDs end up mapping to this API can vary over time, the new features are added to the Web platform, for example. Instead of this, use document.getElementById() or document.querySelector() .

In general, depending on this method ( window[id] ) generates fragile code.

This technology should instead use document.getElementById() or document.querySelector() .

Note:

  

* - named elements are all elements that have the attribute id or name defined.

    
13.04.2016 / 15:05
26

Before there were standards for HTML, CSS and javascript who defined this were browsers, ie each browser had its way of doing things, for example each had a way to get DOM elements, for example :

  • Internet Explorer 4 used document.all
  • Netscape4 used document.layers

These were the main browsers of the "market" and were the ones that first implemented Javascript (in IE it was called Jscript)

From the version of IE5.01, document.getElementById and document.getElementsByTagName was supported, the only one that did not work in IE was document.getElementsByTagName("*"); , which only started to be supported in IE6, so we had to use document.all yet.

The IDs for being "unique" elements in IE (although some developers repeat them, which is a mistake) became accessible directly in the references of global variables that in JavaScript for browsers is the object window , this since the DOM was loaded and the variable had not been declared.

IE has maintained this feature to maintain compatibility with sites that had been made for previous versions, some browsers have imported this feature to try to maintain compatibility

  

My opinion: at the time it was very common to accuse the browser for not working on a particular site, when the problem was in the script, then many engine developers were forced to put those peculiarities in the engines themselves.

In Firefox for example document.layers was still supported, but issued a warning on the console warning it would be removed, otherwise InternetExplorer kept many things like document.all (this sometimes generates a DOM list other than document.getElementsByTagName("*"); ).

There was an engine called iCab (up to version 3 of the browser of the same name for Mac, version 4 onwards started using Webkit and Cocoa API) that had similar functionality to IE4 as document.all , this was a way to maintain compatibility with sites made for IE.

It's likely (there's nothing discussed, it's just a guess) than with the evolution of browsers and "standards" of ECMAScript window generate a variable that represents an element by id automatically is removed one day and only what is really needed is maintained, that is if you use something like window.meuElemento , this may fail in the future.

I also do not recommend using the ID reference because of conflicts with variables that may have been defined and have the same name as id (this is a problem that may already occur and does not depend on the future). >

Note that there are other properties to get DOM elements like:

  • document.forms

    Gets forms by index as document.forms[0]

  • document.embeds

    Gets elements <embed> by index as document.embeds[0]

  • window.frames

    Gets elements <frame> and <iframe> by index as window.frames[0] , note that window.frames does not return the DOM element of (i) frame and yes the object window from inside it, this window.frames[0] then would be the same as doing this document.getElementsByTagName('iframe')[0].contentWindow

13.04.2016 / 15:31
6

The difference is small, it is more in processing time. The "document" is already an element rendered by the Dom, in this sense, when you use getElementById you are capturing the id of the rendered element itself, and there will be no error if the element does not exist in your document. What makes the property safer not to give an error while in window['id_nome'] is captured by the structure of your global window, what happens in this case is that you capture the window array ... There is not much difference in itself, but in the case of window['id_nome'] , an error can occur, especially if you enter the index erroneously, or try to find something that does not exist in the window, also depends a lot on the behavior of the window and the type of browser, IE is medium failed in this question. For if you do not have an appropriate treatment, at some point, you might not find the index of the array, but nothing that can not be solved by the example below:

if (window['id_name']) {
    var el = window['id_name'];
} 

PS: Just be careful with the use of reserved words from the window.

    
13.04.2016 / 15:48