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

Solution 1:

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.

Solution 2:

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