Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript variable corresponds to DOM element with the same ID [duplicate]

Tags:

javascript

dom

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?

like image 684
user560494 Avatar asked Apr 01 '11 15:04

user560494


2 Answers

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.

like image 196
Šime Vidas Avatar answered Oct 21 '22 10:10

Šime Vidas


<!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

like image 2
faebster Avatar answered Oct 21 '22 09:10

faebster