[Solved] JS Error: Uncaught TypeError: Cannot set properties of null (setting ‘innerHTML‘)

Many students have encountered this problem when writing JS code:

Cannot set properties of null (setting ‘innerHTML’). This error means that the null property “innerHTML” cannot be read, which means that the place where you want to insert the written HTML code cannot be found.

Solution: put the script of the read part of the DOM behind the body. Or add window.onload in the script tag and execute this part of the code after the page is loaded.

Reason: when the browser loads the HTML document, it will parse the HTML document into a tree structure called DOM tree. The code is executed from top to bottom. When the innerHTML line of code is executed, it does not load into the following DOM structure, and an error will be reported that the HTML cannot be read.

Example:

<!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>Document</title>
    <script>
        function showTime() {
            var today = new Date;
            var year = today.getFullYear();
            var month = checkNum(today.getMonth() + 1);
            var data = checkNum(today.getDate());
            var hour = today.getHours();
            var minute = checkNum(today.getMinutes());
            var second = checkNum(today.getSeconds());
            var day = today.getDay();
            var a = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
            var tip = 'PM'
            if (hour > 12) {
                hour -= 12;
                tip = 'AM'
            }
            var time = year + 'Year' + month + 'Month' + data + 'date' + ' ' + tip + ' ' + hour + ':' + minute + ':' +
                second + ' ' + a[day];
            document.getElementById('time').innerHTML = time;
        }

        function checkNum(num) {
            if (num < 10) {
                return '0' + num;
            }
            return num;
        }
        setInterval(showTime, 1000);
    </script>
</head>

<body>
    <div id="time"> </div> 
</body>
</html>

Solution: will setInterval(showTime, 1000); Put this line of code after the body:

<body>
    <div id="time"> </div>
</body>
<script>
    setInterval(showTime, 1000);
</script>
</html>

Or add window.onload to the original script tag

        window.onload = function () {
            setInterval(showTime, 1000);
        }
    </script>

This can be solved perfectly!

Read More: