-4

I am working on my website and I want to make a table with a number of rows equal to the length of array game_names, using Javascript. The whole code is:

var game_names = [
  "first_game",
  "second_game",
  "third_game",
  "fourth_game",
  "fifth_game"
];

var parent = document.getElementById("games");

for (i=0;i<=10;i++){
    var child = document.createElement("tr");
    var node = document.createTextNode("hi!");
    child.appendChild(node);
    parent.appendChild(child);
}

In the HTML code is an empty table (without any cells) and with the id "games". The code:

<table id="games" border="10px" align="center" width="100px">         
</table>

For some reason the code doesn't add any rows to the table. I tested that the code runs down when the page is loaded (I put an alert("hi!") to the beginning of the code and it worked). I have no idea what's wrong...

Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120
Simplemathic
  • 77
  • 1
  • 3
  • 13

2 Answers2

0

The code seems to work but would makes strange html. Rows (tr elements) should contain cells (td elements). And your not iterating over your game_names array your just iterating from 0 to ten. See my example of your code below.

var game_names = [
  "first_game",
  "second_game",
  "third_game",
  "fourth_game",
  "fifth_game"
];

var parent = document.getElementById("games");


for (i=0;i<=game_names.length;i++){
    var childRow = document.createElement("tr");
    var childCell = document.createElement("td");
    var node = document.createTextNode("hi!");
    childRow.appendChild(childCell);
    childCell.appendChild(node);
    parent.appendChild(childRow);
}
JB Cooper
  • 89
  • 5
0

Okay I solved the problem. I put the script after the table, because it was in the head tag! Thank you for the answers!

Simplemathic
  • 77
  • 1
  • 3
  • 13