javascript - Cannot set property 'innerHTML' of null while still using window.onload to delay -


i trying write script changes color of text if active screen (there more efficient ways this). error getting uncaught typeerror: cannot set property 'innerhtml' of null javascript (the entire page)

function main() {     var carddiv = '<div id ="cardscreen"><a href="cardscreen.html">';     var card = "card";     var closer = "</a></div>";     var color = (function color1(check) {         if (window.location.href.indexof(check))             return "red";         else             return "white";     });     card.fontcolor = color("cardscreen");     var carddivprint = carddiv + card + closer;     window.onload=document.getelementbyid("header").innerhtml= carddivprint; } main(); 

the html

<!doctype html> <link href="../css/mastersheet.css" rel="stylesheet" /> <html> <head>     <title>     </title> </head> <body>     <div id="header">     </div>     <div>content goes here.</div>  <script src="../scripts/essentials.js"></script> </body>  </html> 

the ide (visual studio 2015 cordova) says error on line in javascript "var carddivprint = carddiv + card + closer;" have looked @ multiple similar problems , applied relevant (also tried changing window.onload document.onload) still throws same error.

onload expects function executed after page loaded. otherwise it'll treat simple assignment statement , execute. use function follow:

window.onload = function() {     document.getelementbyid("header").innerhtml = carddivprint; }; 

update

instead of using main(), use domcontentloaded event.

document.addeventlistener("domcontentloaded", function(event) {     console.log("dom loaded , parsed");      var carddiv = '<div id ="cardscreen"><a href="cardscreen.html">';     var card = "card";     var closer = "</a></div>";      var color = window.location.href.indexof(check) !== -1 ? "red" : "white";      card.fontcolor = color("cardscreen");     var carddivprint = carddiv + card + closer;     document.getelementbyid("header").innerhtml = carddivprint; }); 

Comments