+ 3

JavaScript Problem with document.getElementById().innerHTML

So I'm working on a game and in the HTML I have this: <p><span id="cname">Challenger</span>: <span id="chp">50</span>HP</p> But in the JavaScript, this line: document.getElementById("cname").innerHTML = c.name; gives an error. It says I can't set the innerHTML property of null. But using the same kind of line in a function works just fine. Anybody know what's going on?

22nd Sep 2020, 12:39 AM
Dustin đŸ‡ș🇾
3 Answers
+ 8
Hi Soapyguy [A Bit Inactive with School] Try this! In the Js, the very first line put "window.onload = function () {" And put this at the very last line! "}" And it should work perfectly! The reason you get that error is because sololearn loads the JavaScript file before loading the HTML file and when the JavaScript file loads it's try to find the elements which has that id but since the HTML file hasn't loaded there's no such elements and thus you can't get that element by its ID cuz it is not loaded yet and the reason why functions work is because JavaScript loada functions and variables before the rest of the code that's why it works Hope this help and good luck on your coding adventure â˜•đŸ©!
22nd Sep 2020, 12:52 AM
Vachila64☕
Vachila64☕ - avatar
22nd Sep 2020, 4:22 AM
Raj Chhatrala
Raj Chhatrala - avatar
+ 3
Thanks guys
22nd Sep 2020, 9:37 PM
Dustin đŸ‡ș🇾