views:

50

answers:

1

I have noticed some unexpected behaviour when using the jQuery .ready() function, whereby afterwards you can reference an element in the DOM simply by using its ID without prior definition:

<html>
<script src="jquery.js"></script>
<script>
        $(document).ready(function() {
                myowndiv.innerHTML = 'wow!'
        });
</script>
<body>
        <div id="myowndiv"></div>
</body>

</html>

I would have expected to have to declare and assign myowndiv with document.getElementById("myowndiv"); or $("#myowndiv"); before I could call innerHTML or anything else on it?

Is this behaviour by design? Can anyone explain why? My fear is that if I don't notice and refactor and end up not using .ready() or even using jQuery at all then my code will fail to execute with lots of undefined errors.

Cheers!

+2  A: 

That is a (terrible) Internet Explorer-only "feature". Yet again Microsoft fail at life.... sigh. You will need to do var foo = document.getElementById('foo'); for cross-browser compatibility.

Coronatus
I noticed this first with Safari and have since tested on IE8 and Chrome. Additionally, if you don't do the .ready() then it will fail as expected even on IE, so it appears to be related to jQuery specfically.
Greg
It is not jQuery that's doing it. It's the browser. The reason it fails when you don't put the code in a "ready" function is that when it executes the element you're referencing hasn't appeared in the DOM yet. Try putting a script block (**not** in a "ready" function) at the **end** of the `<body>` and you'll see that the global variables exist at that point.
Pointy
Yep - can see this now. I guess it was introduced in IE and so other vendors have had to keep this 'feature' to ensure sites remain compatible. No wonder browser JavaScript has a bad rep!
Greg
Other vendors do NOT keep the feature, and never did add it because it is not part of the JS standard. JavaScript doesn't have a bad reputation, actually it is sometimes called the language of the future. Microsoft carry the bad reputation.
Coronatus
Hmm, odd as I'd already mentioned that I had tested this on Chrome, Safari and FF? Maybe it's just me- can you try Pointy's answer on your box and make sure if fails in Chrome, Safari and FF please?Here is some code to help you as I wouldn't want you to post a reply without validating your argument first.<html><body> <div id="thedivthatihavenotdefined"></div> <script> for(i = 0; i<100; i++) {var p = document.createElement('p');p.innerHTML = 'This will only work in IE. I hate Microsofts success!';thedivthatihavenotdefined.appendChild(p);} </script> </body> </html>
Greg