0

JavaScript 2D array to table, how to target the table to a div?
The following link talked about create a table from 2D array.
Generate HTML table from 2D JavaScript array
The table was created very well, but the table always shows up at the end of the page.
How to make the table show up in a div?

function createTable(tableData) {
  var table = document.createElement('table');
  var tableBody = document.createElement('tbody');

  tableData.forEach(function(rowData) {
    var row = document.createElement('tr');

    rowData.forEach(function(cellData) {
      var cell = document.createElement('td');
      cell.appendChild(document.createTextNode(cellData));
      row.appendChild(cell);
    });

    tableBody.appendChild(row);
  });

  table.appendChild(tableBody);
  document.body.appendChild(table);
}

createTable([["row 1, cell 1", "row 1, cell 2"], ["row 2, cell 1", "row 2, cell 2"]]);
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Duan Liu
  • 57
  • 1
  • 7

1 Answers1

3

Say you had

<div id="MyTargetDiv"></div>

then you need to change

document.body.appendChild(table);

to

document.getElementById("MyTargetDiv").appendChild(table);
Isaac
  • 11,409
  • 5
  • 33
  • 45
  • Just a cautionary word, be sure to read/understand the code you're putting into your website – Isaac Sep 15 '17 at 01:18