- 2
What is wrong with this code?
13 ответов
0
Денис Сусаров
Again posting:
Try this:
window.onload = function () {
var elem = document.getElementById("demo");
elem.innerHTML = "Hello World!";
}
+ 3
SoloProg
elem is null so that will not work.
Денис Сусаров
Try this:
window.onload = function () {
var elem = document.getElementById("demo");
elem.innerHTML = "Hello World!";
}
+ 3
Thank you)
+ 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.
+ 2
SoloProg
By this solution:
// Or
let elem = document.getElementById("demo");
window.onload = () => {
elem.innerHTML = "Hello World!";
}
elem is still null
+ 2
Денис Сусаров
Check my previous answer.
You should write js code inside window.onload function
+ 1
I get an error "Uncaught TypeError: Cannot set properties of null (setting 'innerHTML') line 2"
+ 1
I get an error "Uncaught TypeError: Cannot set properties of null (setting 'textContent') line 2"
+ 1
// Or
let elem = document.getElementById("demo");
window.onload = () => {
elem.innerHTML = "Hello World!";
}
+ 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.
0
// Try it
elem.textContent = "Hello World!";
0
I get an error "Uncaught TypeError: Cannot set properties of null (setting 'innerHTML') line 6"
- 1
maybe you must place script tag before </body>