0
getElementById in global var returns null
https://code.sololearn.com/Wvl9y8k81g7f Not sure what to do here, as searching for a solution suggests that the DOM isn't loaded when the script is running (hence the readyState comparator). Any advice would be appreciated.
2 Antworten
+ 3
You are trying to delay the execution of your code with the window.onload event, but you still have one getElementById() call in global scope:
var divGame = document.getElementById("g"); // this is executed first, without waiting for document loaded
var gameTags = [ ... ]; // others global var doesn't use DOM, so there's no problem with them
var iconLoc = '...';
function listTags() { // the function you try to call when onload occurs
/* ... */
}
window.onload = listTags(); // you use parenthesis, so your function is called immediatly rather than waiting for document loaded, and onload event listener is (wrong) assigned with the function return value ^^ (in addition, you dupplicate this and do it twice ;)
Instead (if you need to have global var) just declare the 'divGame' without assigning value, and only assign it (by calling getElementById) inside the function called by onload event (by correctly assigning it, of course):
var divGame; // only declaration, no value assigned
var gameTags = [ ... ]; // values no requiring DOM acces can be assigned immediatly
var iconLoc = '...';
function listTags() { // the function you want to call when onload occurs
divGame = document.getElementById("g"); // now you can assign it and almost call getElementById()
/* ... */
}
window.onload = listTags; // without parenthesis, you refer to the function reference itself without running it, with parenthesis you run the function...
+ 1
javascript is executed before the side (and the element) is loaded thats why you get null
try to set it in a actionhandler like a onload or click function