简体   繁体   中英

Uncaught TypeError: Cannot read property 'innerHTML' of null

Keep getting this error, no idea why

Uncaught TypeError: Cannot read property 'innerHTML' of null

My code is:

function write(message) {
  document.getElementById('message').innerHTML += message + '<br/>';
}

function calculateCircumference (diameter) {
    return diameter * 3.14;
}

write (calculateCircumference(4));

Admittedly, the error message is not exactly transparent as to its meaning (but at least you get an error - jQuery would just silently do nothing!)

What it means is that the result of document.getElementById('message') is null. Looking at the docs you will find that this happens when the element cannot be found.

The main reason for an element not being found is because it doesn't exist yet.

<script>// do something with document.getElementById('message');</script>
<div id="message"></div>

The above will FAIL because message does not exist yet. Moving the script after the div will make it work.

Side-note: 3.14 is far too inaccurate. Use Math.PI instead, it's as accurate as a number in JavaScript can be.

Seems that your code is executed before the DOM is ready

window.onload = function(){
    function write(message) {
        document.getElementById('message').innerHTML += message + '<br/>';
    }

   function calculateCircumference (diameter) {
        return diameter * 3.14;
    }

    write (calculateCircumference(4));
}

如果您设置了 id 并且仍然出现相同的错误,请确保您正确完成了 html 的开始和结束标记。

This error is usually caused when the element is not loaded and the js function is trying to access it.

try adding the <script> tag at the very end of the document before </body>

or check if the name of the element is mistyped.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM