views:

357

answers:

1

I don't know if this is a well known 'thing' or something new in whatever version of Firefox it just updated itself too - but in either case I have no idea how to google for this question so I'll have to ask it here.

I have a DIV in my DOM that I am trying to directly access by id, in the most simplest form like this:

 alert(btnTest.id);

This works fine in all browsers, but was causing issues in firefox that actually led to the browser being in a strange 'broken' state.

The error I was getting was 'btnTest is not defined'. I did not get this error in Safari, Internet Explorer or Chrome.

I assumed I had mismatched HTML tags, or javascript curly braces or something else missing. Eventually after stripping everything out I tried removing the DOCTYPE. Suddenly in Firefox (v 3.0.10) it started returning the correct ID as expected.

What is going on!!! ?? Surely 'strict' mode should allow me to access named elements, and if not then why do all the other browsers let me.

Note: I can easily work around it with $('#btnTest')[0].id, which is what I'm going to have to do now until i can figure out a better solution.

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
 <html xmlns="http://www.w3.org/1999/xhtml" class="blueCircles">

 <head>

    <script type="text/javascript"
            src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"&gt;&lt;/script&gt;

    <script>
        $(function() {
            alert("ID retrieved through jQuery: " + $('#btnTest')[0].id);
            alert("ID retrieved by accessing global variable: " + btnTest.id);
        });

    </script>

</head>
<body>
    <div id="btnTest">
    </div>
</body>
</html>
+2  A: 

There is nothing in any W3C specification that says object references should be established in the global scripting scope for elements with id attributes. This is considered to uneccessarily pollute the global namespace and can result in confusing errors.

Firefox establishes the references when running in quirks mode for the purposes of IE compatibility. Johnny Stenback explains in the third comment on the bug for adding this support why this isn't supported in standards mode:

This feature does affect standard compliant code that for instance checks for the existance [sic] of a global variable to set it only once. With this change, that "varible" [sic] may now be a reference to an element in the document, and the code may not work the way the developer intended.

That's the reason we decided to make this quirks only.

Simon Lieschke
great. thanks for providing a real answer !
Simon_Weaver