0

Why getElementBy*something* is not working?

i have HTML: <!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <p id="main"></p> </body> </html> And JS: ob = document.getElementById("main"); ob.innerHTML="hello"; I expect to see just "hello", but it's "Uncaught TypeError: Cannot set property 'innerHTML' of null Line: 3" getElementById() returns null.... What is wrong?

15th May 2018, 7:23 PM
Alexandr Korolev
Alexandr Korolev - avatar
4 Respostas
+ 6
Alexandr Korolev DOM of the HTML document, not built yet and the tags are unreachable. Use this: window.onload=function (){ //your code }
15th May 2018, 7:45 PM
Сергей Луньков
Сергей Луньков - avatar
+ 4
use onload function
15th May 2018, 7:39 PM
Toni Isotalo
Toni Isotalo - avatar
+ 3
Alexandr Korolev You can get an access, directly by ID of the element, like that window.onload=function (){ main.innerHTML='hello'; }
15th May 2018, 7:54 PM
Сергей Луньков
Сергей Луньков - avatar
+ 1
Сергей, спасибо)
15th May 2018, 8:29 PM
Alexandr Korolev
Alexandr Korolev - avatar