+ 1
When i place script tag in head It says that " cannot set property onclick of null. But It work perfectly in body. Help me...
<!doctype html> <html> <head> <script type="text/javascript"> var check=document.getElementById("check"); check.onclick=function al(){ alert("hello")} var b=document.getElementById("demo"); b.addEventListener("click",rand); function rand(){ alert(Math.random())} function change(){ var m=document.getElementById("ch"); m.value=m.value.toUpperCase(); } </script> </head> <body> <br> <button id="check">check me</button> <input type="text" id="ch" onchange="change()"> <button id="demo" >rand</button> <p></p> </body>
5 Réponses
+ 1
Yes the script should loaded after body.
If script is loaded earlier than body it will not found any tag and get the variable as null and error as can't set property of null.
+ 1
Script tag should be added after body tag in order to proper identification of defined id's and classes in document.
0
Divya Mohan Then we have to write on the body all the time? Can't write code on head?
0
You can write code in head but it should not ask for any tag of document otherwise it will show error
You can ask there for
Operation s and console them
0
We should use external js mostly with document.onload/it's link at end of body.
Internal js is not very much good practice it makes file lengthy and haed to analyse