JQuery.ready () automatically defines variables for each element with an identifier in the DOM

I noticed unexpected behavior when using the jQuery .ready() function, after which you can refer to an element in the DOM simply by using your identifier without a 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 suggest that I should declare and assign myowndiv using document.getElementById("myowndiv"); or $("#myowndiv"); before I could call innerHTML or something else on it?

Is this design behavior? Can anyone explain why? I am afraid that if I do not notice and reorganize and do not use .ready() or even using jQuery at all, then my code will not be able to execute with a lot of undefined errors.

Hurrah!

+4
source share
1 answer

This (awful) feature is only for Internet Explorer. But again, Microsoft is failing in life ... a sigh. For compatibility with multiple browsers, you will need var foo = document.getElementById('foo'); .

+3
source

Source: https://habr.com/ru/post/1309985/


All Articles