Cannot create a table with js | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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".

27th May 2020, 9:22 PM
Сергей Куликов
Сергей Куликов - avatar
5 Answers
+ 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
27th May 2020, 9:25 PM
Abhay
Abhay - avatar
+ 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
27th May 2020, 9:42 PM
Abhay
Abhay - avatar
+ 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
27th May 2020, 9:46 PM
Abhay
Abhay - avatar
0
Abhay, thanks. Don't already understand, why, but it works.
27th May 2020, 9:37 PM
Сергей Куликов
Сергей Куликов - avatar
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?
27th May 2020, 9:51 PM
Сергей Куликов
Сергей Куликов - avatar