Javascript get element by id

javascript

Solution

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):

var msg = document.getElementById("msg");

You can read more information about this method in MDN:

- https://developer.mozilla.org/en-US/docs/DOM/document.getElementById

Also, one important note is to use this code when the markup is fully loaded, i.e. when your `msg` element 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>`.

Problem

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?

Original source