I am new to javascript, and I just noticed a javascript behavior that I haven't seen documented anywhere. If I have a DOM element with an assigned id, say "x", then in my javascript, that element is automatically assigned to variable x. I see this in chrome and safari. Is this a documented feature of javascript?
For example:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id='x'>
<input type='text' name='info' id='info'/>
<input type='submit' name='submit' value='Complete'/>
</form>
<script type='text/javascript'>
window.onload = function() {
alert( x==document.getElementById('x') );
info.value = 'Test me!';
}
</script>
</body>
</html>
When loaded, it will alert true, and the input area will show 'Test me!'. If this is the right behavior, why do we need document.getElementById at all?
This behavior is documented in the HTML standard (chapter 6.2.4).
The standard defines "named elements" which are HTML elements that have either a name
or id
attribute set. (Note that the name
attribute is only defined on certain types of HTML elements.)
For each named element, the browser (environment) defines a corresponding global property.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<div id="w"></div>
<script type="text/javascript">
alert( w );
w = null;
alert( w );
</script>
</body>
</html>
Try this test in IE8. You will figure out that w is global and cannot be overwritten. Change "w = null" in "var w = null" and reload (after emptying cache)...
IE8 checks for variables before runtime and removes the global correspondent. I really can't await the day when web developers don't have to support IE8 any more...
HINT: don't use variable names equal to DOM element id's.. OMG OMG
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