Q:

wordpress header javascript - TypeError: document.getElementById(...) is null

I have added this to the header.php: 
<? php wp_head(); ? >
<script>
    console.log('TEST');
    document.getElementById("bestyrelsen").innerHTML = "TEST";
</script>
</head>

And in the page this p tag:
<p id="bestyrelsen"></p>

When the page loads TEST is written to the log, but I get this error:

TypeError: document.getElementById(...) is null

Why is this not working? 

A:

Your code is running before the DOM is fully loaded, wrap your code with DOMContentLoaded which will ensure that the code will be executed when the DOM is fully loaded (all the elements are available):
document.addEventListener('DOMContentLoaded', () => {  
  console.log('TEST');
  document.getElementById("bestyrelsen").innerHTML = "TEST";
});

