[How to Solve] Cannot set property ‘onclick’ of null

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <script>
            //Get this element from the document based on the value of the id attribute
            var btnObj=document.getElementById("btn");
            // for the current button element (object), register the click event, add the event handler (anonymous function)
            btnObj.onclick=function(){
                //response to do something
                alert("jaja");
            };
        </script>
    </head>
    <body>
        <input type="button" value="Display effect" id="btn" />    
    </body>
</html>

After the above code is executed, the

To make changes, you need to put the JS file at the bottom of and load it

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>    
    </head>
    <body>
        <input type="button" value="show effect" id="btn" />    
        <script>
            //get this element from the document based on the value of the id attribute
            var btnObj=document.getElementById("btn");
            // for the current button element (object), register the click event, add the event handler (anonymous function)
            btnObj.onclick=function(){
                //response to do something
                alert("jaja");
            };
        </script>
    </body>
</html>

The code executes normally

Reason: when the JS file is placed in the head, if the onclick or OnMouseOver event is bound, a similar error will appear as shown in the figure above. The reason is that the order of loading the HTML document you write is from top to bottom, and the JS is executed only after the button node is loaded. Therefore, when the browser parses from top to bottom, the button node bound to onclick cannot be found, so an error is reported

The solution: first, load the JS file at the bottom; Second, use window. Onload = function () {} to wrap JS content

Similar Posts: