I encountered "Uncaught TypeError: Cannot set properties of null (setting 'onclick')" problem during my personal study, please share the
html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WEB API学习</title>
</head>
<body>
<button id="btn">母校</button>
<script>
var btn = document.getElementById(" btn ");
btn.onclick =function(){
alert('xtu');
}
</script>
</body>
</html>
Running result:
Cause of the problem: The getElementById method cannot find the written id name (spaces are also considered part of the id name)
Code before modification:
var btn = document.getElementById(" btn ");
After modification:
var btn = document.getElementById("btn");
Run successfully!