+ 5

cannot read property 'value' of null in console

I have a code which runs perfectly on other platforms , but when I try to run the same code in Sololearn Code playground it shows a message: "cannot read property 'value' of null" in console and don't show the output. Actually I make divs inside divs using javascript. So I searched for it and got a solution in Stack Overflow. I implemented it. But the code still not working. Is this possible that same code can show the error (cannot read property 'value' of null) in different plateforms? My code: var ab=document.getElementById('comments'); var comment = document.createElement('div'); comment.setAttribute('class', "comment"); ab.appendChild(comment); Replaced code: var str; var ab=document.getElementById('comments'); var comment = document.createElement('div'); comment.setAttribute('class', "comment"); if (ab != null){ str= ab.appendChild(comment); } else { str = null; } https://stackoverflow.com/questions/22057610/uncaught-typeerror-cannot-read-property-value-of-null

30th Apr 2020, 3:18 PM
Kashyap Kumar
Kashyap Kumar - avatar
3 Answers
+ 3
I Dunno about platform but your js script is getting loaded before html,so obviously you cannot read a property when there exist no property yet ,to avoid that put your js code in Window.onload=function(){ } Or place the script before closing body tag
30th Apr 2020, 3:23 PM
Abhay
Abhay - avatar
+ 6
This is likely happening because Sololearn appends your js to the head of the document, so it runs before the DOM finishes loading. Therefore, when your code tries to get the comments element, it returns null because it hasn't loaded yet. Fix this by wrapping your code in a function that fires on the window.onload event like this: window.onload = ()=>{ //Code here. }
30th Apr 2020, 3:25 PM
Mike Perkowski
Mike Perkowski - avatar
+ 1
Thanks a lot Abhay and Mike Perkowski
30th Apr 2020, 3:31 PM
Kashyap Kumar
Kashyap Kumar - avatar