Why does document.getElementById() function exist?

2019-04-06 12:48发布

问题:

This question already has an answer here:

  • Why don't we just use element IDs as identifiers in JavaScript? 4 answers

when creating web pages I have always used function

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

to get a reference to an element object. It was recently suggested to me that this is not necessary, because there already is such a variable. It's name is equal to the id. I've tested it and it seems to work.

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

This code works and it alerts "some text" as expected. There is just a warning in firefox error console:

element referenced by ID/NAME in global scope. Use WC3 standard document.getElementById() instead....

I am mostly using jQuery by now but I need to prove a point to my boss at work or else I will have have to buy him a box of chocolate :-).

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

Thanks for your answers

回答1:

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

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

Using document.getElementById() ensures that all browsers behave exactly the same (well, more or less cough) when getting a handle to an element.

See bobince's excellent answer to a similar question for more information.



回答2:

element referenced by ID/NAME in global scope. Use WC3 standard document.getElementById() instead....

Your current call would result in possible variable collision.

Picture this:

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

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

You should always use document.getElementById() because it is built for the specific function to retrieve HTML elements and not JavaScript variables.



回答3:

Presumable for cross browser compatibility. The second version doesn't work in Chrome. Which mean it would probably fail in Safari as well.