Method to solve uncaught typeerror: cannot set property ‘onclick’ of null error

Problem analysis: this error occurs when the JS file is placed in the head tag and the onclick event is bound

reason:

W3school introduces that the browser loads the button node before executing JS. When the browser parses from top to bottom, the button node bound to onclick cannot be found

For example:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Events</title> 
<script>
    var Btn = document.getElementById('btn');
    Btn.onclick = function(){    
        console.log("push the button ");        
    }
</script> 
</head> 
<body> 
   <button id="btn">Calculation</button> 
</body>
</html>

This error will appear, as shown in the following figure:

Solution 1: use the JS content in window ο nl ο Ad = function () {} wrap it up

<!DOCTYPE HTML>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Events</title>
    <script>
        window.onload = function () {
            var Btn = document.getElementById('btn');
            Btn.onclick = function () {
                console.log("push the button ");
            }
        }
    </script>
</head>
<body>
    <button id="btn">Calculation</button>
</body>
</html>

Solution 2: load the JS file at the bottom

<!DOCTYPE HTML>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Events</title>
</head>
<body>
    <button id="btn">Calculation</button>
    <script>
        var Btn = document.getElementById('btn');
        Btn.onclick = function () {
            console.log("push the button ");
        }
    </script>
</body>
</html>

Read More: