0
Does this code has any problem?
This code is perfectly running on browser without any error but is failing when run on "code.sololearn.com" with error: ~HTML~ <!DOCTYPE html> <html> <head> </head> <body> <p id="text"></p> </body> </html> ~JavaScript~ let word = document.getElementById('text'); word.innerHTML = 'automatic'; let textNode = word.childNodes[0]; let text = textNode.data; document.write(text); ~Error(As Shown in console of code.sololearn.com)~ TypeError: word is null Line: 8 If any error from my side please let me know. UPDATE: I use standardjs(standardjs.com) for code style with linter which automatically removes semicolons, so I am used to it. Try by running this code on browser and code.sololearn.com
3 Answers
+ 6
just wrap your JavaScript code in this function
onload= function(){
// your code goes here
}
+ 1
@Andreas K
Tried this on code.sololearn.com
~JS~
let word = document.getElementById('text')
word.innerHTML = 'automatic'
This also throws same error :
TypeError: word is null
Line: 8
Following is the code that sololearn's editor sends to code.sololearn.com
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<style>body {
}</style><script>let word = document.getElementById('text');
word.innerHTML = 'automatic';</script></head>
<body>
<p id="text"></p>
</body>
</html>
You would be surprised this code failed in browser also. But if you put script inside body tag at the end it will run perfectly. This is happening because sololearn's editor is sending script in head tag and at that time #word is null. But when script is added in body tag it works perfectly.
Do tell me if there's any hole in my logic
Thanks.
0
The logic seems fine. By using window.onload(()=>{}) it should work