tehaaron tehaaron - 1 month ago 8
Javascript Question

Generate a 4 column table from javascript array data

My question is very similar to How to Generate 3x3 HTML Table From an JavaScript Array the only problem is that the answer I prefer in that thread I cant seem to make work (I like it because it does not use innerHTML).

My current code:

var alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
var table = document.createElement("table");
var i = 0;
for (var r = 0; r < 4; r++) {
var row = table.insertRow();
for (var c= 0; c < 4; c++) {
var cell = row.insertCell();
cell.appendChild(document.createTextNode(alphabet[i++]));
}
}

document.body.appendChild(table);


Basically when I include this .js file in my html document nothing happens. I tried creating a table and loading it inside of it also, but that did nothing. I am probably missing something obvious here.

Answer

Try

window.onload = function() {
  var alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
  var table = document.createElement("table");
  var i = 0;
  for (var r = 0; r < 4; r++) {
    var row = table.insertRow(r);
    for (var c = 0; c < 4; c++) {
      var cell = row.insertCell(c);
      cell.appendChild(document.createTextNode(alphabet[i++]));
    }
  }

  document.body.appendChild(table);
}

Comments