4

I have tried several methods of writing to this div, but to know avail:

The 'testing' works, but nothing else:

document.write("testing");
document.getElementById('menu2').innerHTML += "<br>Some new content!";
var node = document.getElementById("menu2");
node.innerHTML = "<p>" + "Hello" + "</p>";
(function printMsg() {
    var node = document.getElementById("menu2");
    node.innerHTML = "<p>" + "Hello World!" + "</p>";
})();

and in the html

<div id="menu2">x</div>

the x shows

As of this writing, this is at http://www.jchess.nyc (index page)

Jerry
  • 59
  • 1
  • 3

2 Answers2

2

That happens because document.write just writes the text you specify in body; it's not required for any element to be loaded to be able to document.write, but document.getElementById() searches for the element in DOM, which isn't created immediately when you begin executing your script, so your script is trying to access your element with id menu2 before it is loaded.

To be able to use document.getElementById(), you should wait for the DOM to load, by placing all your methods accessing DOM to:

window.onload=function(){

}
nicael
  • 16,503
  • 12
  • 50
  • 80
  • 1
    *"document.write just overwrites all your html in the "*. In OP's case it doesn't happen, because `document` is still open (being rendered). So `document.write` just appends text to the document and doesn't overwrite body. – dfsq Mar 29 '15 at 14:15
  • @dfd fair enough; edited. – nicael Mar 29 '15 at 14:17
2

You problem is that you put script in the begining of the body, so it's executed before div#menu2 is avaialable in DOM.

The simplest fix is to move script tag before closing </body> tag. Also remove document.write, it's not a problem here but you don't need it.

<script>
document.getElementById('menu2').innerHTML += "<br>Some new content!";

var node = document.getElementById("menu2");
node.innerHTML = "<p>" + "Hello" + "</p>";

(function printMsg() {
    var node = document.getElementById("menu2");
    node.innerHTML = "<p>" + "Hello World!" + "</p>";
})();
</script>

</body>
dfsq
  • 182,609
  • 24
  • 222
  • 242
  • I would also cache the element at the beginning rather than pick it up at three different points in the code, but that's an aside. – Andy Mar 29 '15 at 14:17