Why isn't this table being sorted correctly?

Viewed 49

Don't know why the table isn't being sorted into rows and columns correctly. I am attempting to create a two dimensional array, and then use nested for loops to automatically create a table.

list = [
  [12, 4, 22],
  [11, 32, 7],
  [9, 16, 13]
];
for (var i = 0; i < list.length; i++) {
  tablebody.innerHTML += "<tr>";
  for (var j = 0; j < list[i].length; j++) {
    tablebody.innerHTML += "<td>" + list[i][j] + "</td>";
  }
  tablebody.innerHTML += "</tr>"
}
body {
  background-color: black;
  color: white;
}
<table id="table">
  <thead id="tablehead">
    <tr>List[0]</tr>
    <tr>List[1]</tr>
    <tr>List[2]</tr>
  </thead>
  <tbody id="tablebody">
  </tbody>
</table>

2 Answers

You can't add fragements to innerHTML. When you do tablebody.innerHTML+="<tr>";, the browser automatically adds a closing </tr> right after.

You need to build the string into its own variable, then do tablebody.innerHTML = yourTableVar; afterwards.

var tableData = '';

for (var i = 0; i < list.length; i++) {
  tableData += "<tr>";
  for (var j = 0; j < list[i].length; j++) {
    tableData += "<td>" + list[i][j] + "</td>";
  }
  tableData += "</tr>"
}

tablebody.innerHTML = tableData;

Also, your HTML for for your <thead> is incorrect. You need to have a <tr> as your header row and <th> tags with your column headers:

<thead id="tablehead">
    <tr>
        <th>List[0]</th>
        <th>List[1]</th>
        <th>List[2]</th>
    </tr>
</thead>

const tablebody = document.querySelector('table#table tbody')
  ,   list =
       [ [ 12,  4, 22 ]
       , [ 11, 32,  7 ]
       , [  9, 16, 13 ]
       ]
for (let row of list) 
  {
  let nRow = tablebody.insertRow()
  for( let vCol of row)
    {
    nRow.insertCell().textContent = vCol
    }
  }
body {
  background-color : black;
  color            : white;
  }
table  {
  border-collapse  : collapse;
  }
table td {
  padding    : 5px;
  width      : 20px;
  height     : 20px;
  border     : 1px solid green;
  text-align : center;
  }
table thead {
  background-color : darkblue;
  }
<table id="table">
  <thead>
    <tr>
      <td>List[0]</td>
      <td>List[1]</td>
      <td>List[2]</td>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

Related