JavaScript Uncaught TypeError: Cannot set property ‘innerHTML’ of null”

Wrote a function and got an error when calling.”Uncaught TypeError: Cannot set property ‘innerHTML’ of null”

Code Below

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script>
            var func3 = function(a,b){
                return a + b
            }
            console.log(func3(1,2))
            var x = func3(99, 1)
            console.log(x)
            document.getElementById('demo').innerHTML = x;
            
        </script>
    </head>
    <body>
        <p id=demo>The value to be modified</p>
    </body>
</html>

explains: the reason for the error is that the innerHTML in document is empty, that is to say, when loading the JS file, the object called is the &lt in the text. p> Label

Therefore, you need to place the JS file reference in <p> After the label, i.e

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script>
            var func3 = function(a,b){
                return a + b
            }
            console.log(func3(1,2))
            
        </script>
    </head>
    <body>
        <p id=demo>The value to be modified</p>
        <script>    
            var x = func3(99, 1)
            document.getElementById('demo').innerHTML = x;
        </script>
    </body>
</html>

Conclusion: this small problem exposes the problem of understanding the loading order of HTML files. That is, the content in html is loaded in the order of HTML itself

Therefore, when introducing JS or adding <script> Content is executed after HTML content

Similar Posts: