+7

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

11/15/2019 6:34:50 PM

Dron Solarice

7 Answers

New Answer

+18

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.

+6

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 :(

+3

Try to use Window.onload= function (){ //Js stuff } Or put your js code in script tag Actually you Dom is loaded before window that's why this happens

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

0

Have you linked to your js script? And if so, put the link at the bottom after all the divs have loaded.

0

Coder is right, but I think you need a semicolon after window.onload = function(){ //Js stuff }; ^

0

in js in line 5 you wrote „txt“ instead of the id-text: „text“ . is it what you were looking for?