0

I have the following div in HTML:

<div id = "datum">contents here</div>

In JavaScript I have the following code to display the date:

var myDate= new Date();
document.getElementById('datum').innerHTML = myDate;

I get the following error in my console:

TypeError: document.getElementById(...) is null script.js:5:5

I have already tried to put the code above the div tag, since JavaScript reads from top to bottom, but it is still the same issue.

Thank you in advance.

RobG
  • 124,520
  • 28
  • 153
  • 188
  • Does document.getElementById('datum') actually produce any results in your page? Can you type it in console and post what comes back? – shmow Jul 04 '17 at 12:22
  • No relation with java, Java and Javascript are completly differente languages – azro Jul 04 '17 at 12:22
  • ReferenceError: document is not defined at Object. at Module._compile (module.js:409:26) at Object.Module._extensions..js (module.js:416:10) at Module.load (module.js:343:32) at Function.Module._load (module.js:300:12) at Function.Module.runMain (module.js:441:10) at startup (node.js:139:18) at node.js:968:3 –  Jul 04 '17 at 12:24
  • "*I … put the code above the div tag*" so the div doesn't exist when the code runs, so `document.getElementById('datum')` returns `null`, hence the error saying it's null. – RobG Jul 05 '17 at 00:48

1 Answers1

1

Your code may not be getting executed after the DOM loads. Try the following:

document.addEventListener('DOMContentLoaded', function() {
    var myDate= new Date();
    document.getElementById('datum').innerHTML = myDate;
});
User 328 6227
  • 1,141
  • 1
  • 10
  • 14
Puneet
  • 195
  • 11