There is nothing asynchronous in this code, you must be getting confused with the order in which the files are loaded in your browser (which is an asynchronous process).
And because I have to put mine in my body to work, and not in
head?
It depends on how you are including the script in the HTML. If you are including way inline (writing the script in the same file), the script will be executed immediately. This means that the getElementById
will only be able to fetch elements that have already been loaded, so these elements need to be declared before the script.
If the script is declared in another file, in the style
<script src="meuscript.js"></script>
This means that it will be loaded on a different request, asynchronously. This means that until it is loaded, it is possible that all of your HTML is already loaded/processed, and so, even if the script is stated in the head, it is likely (but not guaranteed) that he can read elements of the body with the getElementById
.
For these cases you need to use attributes in the script element, or in Javascript, so that the code is only executed after the HTML is already loaded.
Behold What is a Table Test? How to Apply It?
– Augusto Vasques
Related: What is the difference between $(Document). ready() and window.onload?
– Jéf Bueno
On your second question: in the head your code is loaded very early (before the page itself is mounted by the browser) and therefore the method
guess
will not find the elements with the informed id’s. Making the call by body the page will already have loaded when the script is executed and therefore works as expected.– Jéf Bueno
Is there any way to load these id’s before? And it is recommended ?
– Thomson