Why is there a document.getElementById () function?

When creating web pages, I always used the function

var someVariable = document.getElementById('myID'); 

to get a link to the item object. I was recently suggested that this is not necessary because such a variable already exists. This name is id. I tested it and it works.

 <div id="myID">some text</div> <a href="someplace" onclick="alert(myID.innerHTML)">click here</a> 

This code works and it warns "some text" as expected. There is a warning in the firefox console:

referring to ID / NAME in global area. Use WC3 standard document.getElementById () instead.

I mostly use jQuery, but I need to prove that my boss is at work, or I have to buy him a box of chocolate :-).

Any ideas why the top code should not work or why it is a very wrong idea to use it (warning in firefox is not enough) ???

thank you for your responses

+8
javascript getelementbyid
source share
3 answers

Any ideas why the top code should not work or why it is a very wrong idea to use it (warning in firefox is not enough) ???

Because it is non-standard ( but not for long ). Although some browsers assign elements with an identifier to global variables, there is no obligation for them (and not all of them). Older versions of Firefox, for example, do not exhibit this behavior. There is also the risk of naming collisions .

Using document.getElementById() ensures that all browsers will behave in exactly the same way (well, more or less cough) when receiving an element descriptor.

See bobince's excellent answer for more details.

+10
source share
Element

referenced by ID / NAME, in global reach. Use the WC3 standard document.getElementById () instead.

Your current call will result in a possible collision of variables.

Figure this out:

 <script> var myID = 'foo'; </script> <div id="myID">some text</div> <a href="someplace" onclick="alert(myID.innerHTML)">click here</a> 

myID now not your HTML element, but a variable containing "foo". Example.

You should always use document.getElementById () because it is designed for a specific function to extract HTML elements, not JavaScript variables.

+8
source share

Compatibility with the browser is supposed. The second version does not work in Chrome. This means that he is also likely to fail in Safari.

+1
source share

All Articles