-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>

4
  • Java is not javascript. Please change the title and content so people arent confused. Commented Jul 24, 2020 at 12:45
  • Maybe you should open your browser's console and see the errors you're getting. Commented Jul 24, 2020 at 12:51
  • A couple of quick suggestions: Cell1 and cell1 are different things. And so are ; and ,. Commented Jul 24, 2020 at 12:53
  • There is more wrong with this than right. Throw this all away, read the duplicate, start again. Commented Jul 24, 2020 at 12:57

2 Answers 2

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>

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

Comments

-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>

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.