What is wrong with this code? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
25th May 2022, 11:01 AM
Денис Сусаров
Денис Сусаров - avatar
13 Answers
0
Денис Сусаров Again posting: Try this: window.onload = function () { var elem = document.getElementById("demo"); elem.innerHTML = "Hello World!"; }
25th May 2022, 11:19 AM
A͢J
A͢J - avatar
+ 3
SoloProg elem is null so that will not work. Денис Сусаров Try this: window.onload = function () { var elem = document.getElementById("demo"); elem.innerHTML = "Hello World!"; }
25th May 2022, 11:15 AM
A͢J
A͢J - avatar
+ 3
Thank you)
25th May 2022, 11:21 AM
Денис Сусаров
Денис Сусаров - avatar
+ 3
Денис Сусаров The reason behind this is that Sololearn loads JS code first then html contents so you cannot get element in JS so you need to load JS code after html contents using window.onload function.
25th May 2022, 11:26 AM
A͢J
A͢J - avatar
+ 2
SoloProg By this solution: // Or let elem = document.getElementById("demo"); window.onload = () => { elem.innerHTML = "Hello World!"; } elem is still null
25th May 2022, 11:17 AM
A͢J
A͢J - avatar
+ 2
Денис Сусаров Check my previous answer. You should write js code inside window.onload function
25th May 2022, 11:18 AM
A͢J
A͢J - avatar
+ 1
I get an error "Uncaught TypeError: Cannot set properties of null (setting 'innerHTML') line 2"
25th May 2022, 11:08 AM
Денис Сусаров
Денис Сусаров - avatar
+ 1
I get an error "Uncaught TypeError: Cannot set properties of null (setting 'textContent') line 2"
25th May 2022, 11:15 AM
Денис Сусаров
Денис Сусаров - avatar
+ 1
// Or let elem = document.getElementById("demo"); window.onload = () => { elem.innerHTML = "Hello World!"; }
25th May 2022, 11:16 AM
SoloProg
SoloProg - avatar
+ 1
try this: window.onload = function(){ var elem = document.querySelector("#demo"); elem.innerText = "Hello World!"; } try innerText not innerHTML because when you want to load another html code that is when innerHTML should be use but if you want to load text i advice you to use innerText.
26th May 2022, 7:20 AM
Daudasaeed
Daudasaeed - avatar
0
// Try it elem.textContent = "Hello World!";
25th May 2022, 11:13 AM
SoloProg
SoloProg - avatar
0
I get an error "Uncaught TypeError: Cannot set properties of null (setting 'innerHTML') line 6"
25th May 2022, 11:17 AM
Денис Сусаров
Денис Сусаров - avatar
- 1
maybe you must place script tag before </body>
25th May 2022, 11:13 AM
Irfan akbari habibi
Irfan akbari habibi - avatar