Possible Duplicate:
IE/Chrome: are DOM tree elements global variables here?
why window[id] === document.getElementById( id )
I've just come across something in html/javascript which has surprised me a bit. When obtaining a reference to an html element, using javascript, I have always previously used either jQuery or document.getElementById. It also appears that you can directly access a element simply by using it's id. Can someone explain the nuances of this? I've googled but cannot find any reference to this ability, every site talks about getElementById.
The following page snippet illustrates this.
<html>
<head>
</head>
<body>
<input type="button" value="getElement" onclick="document.getElementById('blah').innerText = 'getElementById'" />
<input type="button" value="direct" onclick="blah.innerText = 'direct';" />
<div id="blah"></div>
</body>
Many thanks in advance.
Being able to select elements on the page based on their [id] is a "feature" from early JavaScript (DOM lvl 0 or 1 methinks, can't seem to find the source).
Unfortunately it's a temperamental feature. What would happen if you had:
<div id="window"></div>
or
<div id="document"></div>
Better yet, what happens here?
<div id="foo"></div>
<div id="bar"></div>
<script>var foo = document.getElementById('bar');</script>
So the nuances to calling an element based on it's [id] is simply this:
It's not consistent, and not guaranteed to receive future support.
Personally I'd like to see this "feature" go the way of document.all. It only causes more issues than it solves, and document.getElementById, while certainly verbose, is meaningful and understandable.
Using getElementById is more flexible and readable. For instance, this won't work:
<input type="button" value="direct" onclick="document.innerText = 'direct';" />
<div id="document"></div>
for obvious reasons, but this will:
<input type="button" value="getElement" onclick="document.getElementById('document').innerText = 'getElementById'" />
<div id="document"></div>
and it's more clear to other developers what's really going on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With