Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does document.getElementById() function exist? [duplicate]

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

like image 589
Voooza Avatar asked Feb 18 '11 14:02

Voooza


2 Answers

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.

like image 74
Andy E Avatar answered Oct 03 '22 04:10

Andy E


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.

like image 42
Aron Rotteveel Avatar answered Oct 03 '22 04:10

Aron Rotteveel