Javascript is executed in a top-down order. Unless you specify otherwise, the Javascript code will not wait until the page is loaded before executing. For example, a web page contains the following HTML code:
If you add the following Javascript code before this line of HTML code:
Run this page, you will get this error message: "document.getElementById('ele') is null." The reason is that when the above javascript is run, there is no DOM element with the ID 'ele' on the page yet.
There are two solutions:
1. Put the javascript code after the HTML code:
2. Wait until the web page is loaded and run the javascript code. You can use the traditional solution (load): first add the HTML body and add "," and then call the above javascript code in the load() function. What I want to focus on here is to use jQuery to achieve it:
< ;script>
$(document).ready(function(){
document.getElementById('ele').innerHTML= 'welcome to my blog';
});
script>
//Of course, since jQuery is used, the simpler way to write it is:
<script><br>$(document).ready(function(){<br> $('#ele' ).html('welcome to my blog'); //The .text() method is also available here<br>});<br></script>
You can put the above jQuery No matter where the code is placed on the page, it will always wait until the page is loaded before executing.