+ 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>

21st Sep 2020, 8:19 AM
MUHAMMED SUHAIL
MUHAMMED SUHAIL - avatar
5 odpowiedzi
+ 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.
21st Sep 2020, 12:00 PM
Divya Mohan
Divya Mohan - avatar
+ 1
Script tag should be added after body tag in order to proper identification of defined id's and classes in document.
21st Sep 2020, 12:12 PM
AMAN GUPTA
AMAN GUPTA - avatar
0
Divya Mohan Then we have to write on the body all the time? Can't write code on head?
21st Sep 2020, 12:10 PM
MUHAMMED SUHAIL
MUHAMMED SUHAIL - avatar
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
21st Sep 2020, 12:30 PM
Divya Mohan
Divya Mohan - avatar
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
21st Sep 2020, 12:32 PM
Divya Mohan
Divya Mohan - avatar