+ 23

Why can't I use innerHTML property in my codes?

I can't use innerHTML property in my codes when I use Sololearn playground. Any advice how to fix that? https://code.sololearn.com/Wlhd8rzsH5IQ/?ref=app

15th Nov 2019, 6:34 PM
Dron Solarice
Dron Solarice - avatar
7 Réponses
+ 33
Well, it's a pretty common beginners mistake. And it's not line 5 (although there is one), the code execution stops at line 3, where the first error is encountered, Mylisa_beth. Everything is linked properly Xyenia 🦉. In fact everything is done by the playground. You can't really see it but all the "links" are located in the head section. This is the most common and preferred way. Why does it happen? The parsing of the HTML document is done in a old fashioned way. The code is read and executed line by line, which means the head elements (and linked JavaScript & CSS files) are parsed before the body section. That's why your variables are declared before any element is loaded on your page. Missing elements are null, which cannot have innerHTML property. At that point the assignment operator (=) raises an error. You need to delay the script execution until the page is fully loaded. Using defer attribute in the script tag could help. But you can't edit that one, so the Coder's solution the best here.
18th Nov 2019, 9:44 PM
🇺🇦 Drake CDR 🇺🇦
🇺🇦 Drake CDR 🇺🇦 - avatar
+ 16
Thank you for the answer Xyenia 🦉 but alas that didn't help me. It makes no sense because I just made an examle code. I don't want anything special. I want to read contents of the elements BEFORE any manipulation or assignment which wouldn't work anyway after an error :(
15th Nov 2019, 9:12 PM
Dron Solarice
Dron Solarice - avatar
0
You haven't manipulated the innerHTML, just declared variables with no modification or assigned value to what the document element should be. Check here for an idea https://www.w3schools.com/jsref/prop_html_innerhtml.asp
15th Nov 2019, 6:54 PM
Xyenia 🦉
Xyenia 🦉 - avatar
0
Have you linked to your js script? And if so, put the link at the bottom after all the divs have loaded.
15th Nov 2019, 9:55 PM
Xyenia 🦉
Xyenia 🦉 - avatar
0
Coder is right, but I think you need a semicolon after window.onload = function(){ //Js stuff }; ^
16th Nov 2019, 5:17 AM
Biglegsbigteeth
Biglegsbigteeth - avatar
0
in js in line 5 you wrote „txt“ instead of the id-text: „text“ . is it what you were looking for?
17th Nov 2019, 6:38 PM
Mylisa_beth
Mylisa_beth - avatar