0

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.

2 Answers 2

1

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);
}

Sign up to request clarification or add additional context in comments.

2 Comments

This combined with <body onLoad="load()"> in the html file did the trick. Thanks!
The comment above is no longer relevant.
0

Don't just include, put this in onload

<script type="text/javascript">
function load()
{
// your code here
}
</script>
</head>

<body onload="load()">

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.