1. 程式人生 > 實用技巧 >Cannot set property ‘innerHTML’ of null 錯誤原因

Cannot set property ‘innerHTML’ of null 錯誤原因

js檔案中呼叫了html中的某個節點,並且js在這個呼叫的物件之前載入了。
如果js放在頭部時,此時瀏覽器渲染未進入dom節點,因為提示為空,或者找不到。
所以把js程式碼放到最後或呼叫的物件後面就行了。

錯誤程式碼:

<!DOCTYPE html>
<html lang="en-US">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Today's Date</title>
    <script type ="text/javascript">
        let d = new Date();
        document.body.innerHTML = "<h1>Today's date is " + d + "</h1>"
    </script>
</head>

<body>

</body>
</html>

修改:

<!DOCTYPE html>
<html lang="en-US">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Today's Date</title>

</head>

<body>
    <script type ="text/javascript">
        let d = new Date();
        document.body.innerHTML = "<h1>Today's date is " + d + "</h1>"
    </script>
</body>

</html>