-3

I am not familiar with JavaScript and HTML. Just want to build a Table with JavaScript in HTML. I am following some instructions, part of code is as bellow. would you please let me know what is the problem that the table is not appearing?

    tb1= document.createElement('table');
    var tr = tb1.insertRow();
    var Cell1 = tr.insertCell(0),
    var Cell2 = tr.insertCell(1),
    var Cell3 = tr.insertCell(2),
    var Cell4 = tr.insertCell(3);
    cell1.innerHTML = "11";
    cell2.innerHTML = "11";
    cell3.innerHTML = "11";
    cell4.innerHTML = "11";
    tb1.appendChild(MyTable);
    <table id="MyTable" width="100%" ></table>
Liam
  • 27,717
  • 28
  • 128
  • 190
MohoTa
  • 27
  • 1
  • 1
  • 9

2 Answers2

1
  1. You don't have to use document.createElement('table'); if the element is in your html, use getElementById("MyTable");
  2. You are using commas instead of semicolon in the end of lines;

There is an example that could make you understand better:

window.onload = function() {
   var table = document.getElementById("myTable");
   var row = table.insertRow(0);
   var cell1 = row.insertCell(0);
   cell1.innerHTML = "1";
    
   var row = table.insertRow(1);
   var cell1 = row.insertCell(0);
   cell1.innerHTML = "1";
    
   var row = table.insertRow(2);
   var cell1 = row.insertCell(0);
   cell1.innerHTML = "1";
};
table, td {
          border: 1px solid black;
        }
 <table id="myTable"> </table>
Liam
  • 27,717
  • 28
  • 128
  • 190
Murilo Góes de Almeida
  • 1,588
  • 5
  • 20
  • 42
-2

var div= document.getElementById('MyTableContainer');
var tb1= document.createElement('table');
var tr = tb1.insertRow();
var cell1 = tr.insertCell(0);
var cell2 = tr.insertCell(1);
var cell3 = tr.insertCell(2);
var cell4 = tr.insertCell(3);
cell1.innerHTML = "11";
cell2.innerHTML = "11";
cell3.innerHTML = "11";
cell4.innerHTML = "11";
div.appendChild(tb1);
#MyTable > table {
  width: 100%;
}

td {
border: 1px solid;
}
<div id="MyTableContainer" width="100%" ></div>
Shivaji Mutkule
  • 1,020
  • 1
  • 15
  • 28
  • 2
    This *could* be a good answer but you need to do more than just vomit some code into it. As it stands it's just a poor answer to a poor question – Liam Jul 24 '20 at 12:54