jQuery .ready() automatically assigning variables for each element with ID in DOM
- by Greg
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!