+ 1

Trying to make a simple digital clock, running into a DOM problem

https://code.sololearn.com/Wqpt5i7YgYi2/#js I've been trying to do some basic exercises to cement the knowledge gained from the fundamental courses and the digital clock is doing my head in. I can get a functional basic clock going with the bare minimum of JS, but the above keeps running into a DOM problem. The error is: TypeError: document.getElementById(...) is null Googling has led me down a few paths, which I've document as comments in the HTML section as I attempted them, but so far I can't get the order right to make it load and run properly. I've gotten to the point that I understand that it's a problem with the code calling for an element that doesn't exist yet, so I know that is what I have to fix, but I can't figure out how to make that happen. I think I could get it working if I move the entire JS section into a script inside the HTML below the div, because then the order should be good, but I'd like to get it working in the current construction rather than cutting and pasting half the code (If it's at all possible). If someone could help me figure out where I'm going wrong I would greatly appreciate it!

15th Sep 2018, 6:18 PM
Rik van Straaten
3 Answers
+ 1
I'm seeing more and more people getting this kind of problems you are calling the script before loading the window so you could solve that writing the script at the end of your html or write everything in js inside window.onload(){ //code } oh and instead of using innertext you need to use innerHTML btw Rik van Straaten ben jij ook nederlands?
15th Sep 2018, 6:24 PM
Roel
Roel - avatar
+ 4
Change your last line to: window.onload = showTime; your JS is loaded before the DOM is completely loaded, therefore the elements you are trying to target does not exists yet i made a post about this a while back https://www.sololearn.com/post/7444/?ref=app
15th Sep 2018, 6:21 PM
Burey
Burey - avatar
+ 4
@Roel: Thanks, simply moving it into the HTML worked, as I mentioned above that was my next course of action, but I was under the impression that I could somehow get it working within the JS section. I imagine the codepen.io example I used confused me, because in that example the code was in the JS section. At the very least, it's working now as a script tag inside the HTML below the div so I'm happy with that. Thank you (And you too Burey!) for your assistance! Edit: En ja @Roel! De naam geeft het wel een beetje weg ;)
15th Sep 2018, 6:33 PM
Rik van Straaten