Cannot set property 'innerHTML' of null

Joshua W picture Joshua W · Aug 14, 2013 · Viewed 381.1k times · Source

Why do I get an error or Uncaught TypeError: Cannot set property 'innerHTML' of null? I thought I understood innerHTML and had it working before.

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Document</title>

<script type ="text/javascript">
    what();
    function what(){
        document.getElementById('hello').innerHTML = 'hi';
    };
</script>

</head>

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

Answer

Erik Godard picture Erik Godard · Aug 14, 2013

You have to place the hello div before the script, so that it exists when the script is loaded.