How to Solve Error: Cannot set property ‘onclick’ of null

Today, I saw a test case of w3school JS click event http://www.w3school.com.cn/tiy/t.asp?f=js_ dom_ event_ Onclick4, its code is:

<!DOCTYPE html>
<html>
<head>
</head>
<body>

<p>The <em>displayDate()</em> function can be executed by clicking the button. </p>

<button id="myBtn"> click here</button>

<script>
document.getElementById("myBtn").onclick=function(){displayDate()};
function displayDate()
{
document.getElementById("demo").innerHTML=Date();
}
</script>

<p id="demo"></p>

</body>
</html>

The click effect is normal. When I test code, I usually write JS code in the head tag. If the JS code is moved to the head tag, the browser will report an error and prompt: uncaught type error: cannot set property ‘onclick’ of null

After analyzing the code, w3school is written as JS after the browser loads the button node, so I changed the code to:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
window.onload=function(){
	document.getElementById("myBtn").onclick=function(){displayDate()};
	function displayDate(){
		document.getElementById("demo").innerHTML=Date();
	}
}

</script>
</head>
<body>

<p>The <em>displayDate()</em> function can be executed by clicking on the button. </p> <button id="myBtn"> click here</button>

<p id="demo"></p>


</body>
</html>

The test passed, indicating that the node needs to be loaded before the onclick event can be executed

 

 

 

Similar Posts: