My HTML includes the code:
<div id="msg"></div>
In its body.
In the head section I then have:
var msg = document.getElementByID("msg");
But when I then call within a function:
msg.innerHTML = "test";
It returns an error stating that msg is null. What should I do?
Firstly, you have to consider that JavaScript is case sensitive language, so you should use
getElementById(note case of last letter). Next, if you get element by id, you should pass ID as an argument (not a tag name):You can read more information about this method in MDN:
Also, one important note is to use this code when the markup is fully loaded, i.e. when your
msgelement is “visible” for JavaScript. In order to achieve this, one option is to put your<script>tag (with corresponding JavaScript code) to the end of HTML right before</body>.