jQuery .ready() automatically assigning variables for each element with ID in DOM

Posted by Greg on Stack Overflow See other posts from Stack Overflow or by Greg
Published on 2010-05-17T13:02:48Z Indexed on 2010/05/17 13:10 UTC
Read the original article Hit count: 182

Filed under:
|

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 declaration or assignment:

<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 refactor and end up not using .ready() or even using jQuery at all then my code will fail to execute.

Cheers!

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about JavaScript