0
Cannot create a table with js
I want to create a table in a div container (<div id="gamePlot"></div>). Cannot understand, why my code doesn't work. Please help. var gamePlot = document.getElementById("gamePlot");//ok var gameTable = document.createElement("table");//ok gamePlot.appendChild(gameTable);//console writes "cannot read property 'appendChild' of null".
5 Réponses
+ 2
Add this js script inside this function then run it again
window.onload=function(){
}
this function prevents js from running before html is loaded
+ 2
Сергей Куликов look Html should be loaded before js ,so when js try to access the element it can do so easily without any error,
But sometimes js gets loaded before html ,and in that case getElementByID doesn't works as there exist no element with that id yet and null error is returned
So in order to stop that window.onload function runs js after the main page html with its elements get loaded fully
Hopefully this all makes sense
+ 2
Also you can search for similar questions ,it has been asked many times, why does it return null or so, you had get much better answers and links that can help you understand it briefly
0
Abhay, thanks. Don't already understand, why, but it works.
0
Abhay I tried to put whole my script into the onload function but it stopped to work. Do I need to put every 'getElement...' which are not placed into another blocks methods into window.onload function?