+ 3

Why can't I use InnerHTML to change the content of an id when the JS script is from an external file.

The InnerHTML property returns null each time I tried to change the value of an "id" when the script tag is in the head or in an external file. But whenever I put the scrip tag at the bottom of the body, the value of the InnerHTML changes to the required value. Where did I go wrong, even after following the correct syntax?

16th Oct 2018, 12:05 PM
AWI
AWI - avatar
4 Answers
+ 2
The easy way: make sure that your code is executed after the document is loaded using window.onload event: window.onload= function(){ // from here you can get all reference to DOM without problem }
16th Oct 2018, 1:05 PM
KrOW
KrOW - avatar
+ 3
Browsers load html in the order tags are placed. In the head the JS gets loaded before HTML which means you cant access the DOM.
16th Oct 2018, 12:09 PM
TurtleShell
TurtleShell - avatar
+ 2
Is not the innerHTML property to return null, but the element itself... If you get a reference to DOM (like with document.getElementById et familty) BEFORE that element is loaded, you will get null like reference... In practice you have to make sure that element is YET loaded before get a reference to it. Because of this all work when you put to bottom of body (elements are yet loaded) but not when you put the script in head (elements are not loaded yet)
16th Oct 2018, 12:12 PM
KrOW
KrOW - avatar
+ 1
KrOW pls how do I go about it...
16th Oct 2018, 1:01 PM
AWI
AWI - avatar