Alvin Alvin - 3 months ago 11
HTML Question

Add row into existing table

May I know how do I insert items into my table body? My code doesn't seems to work.



var tableRef = document.getElementById("myList").getElementsByTagName("tbody");

var newRow = tableRef.insertRow(tableRef.rows.length);

var newCell = tableRef.insertCell(0);

var myTextTwo = "hello world";

var newText = document.createTextNode(myTextTwo);

newCell.appendChild(newText);

<table id="myList">
<thead>
<tr>
<td>Product ID</td>
<td>Product Name</td>
<td>Quantity</td>
</tr>
</thead>
<tbody>

</tbody>
</table>




Answer

getElementsByTagName returns an array. You need to append [0] to select the first element in the array.

You are also trying to use insertCell on tableRef, when you should be using it on newRow:

var tableRef = document.getElementById("myList").getElementsByTagName("tbody")[0];

var newRow = tableRef.insertRow(tableRef.rows.length);

var newCell = newRow.insertCell(0);

var myTextTwo = "hello world";

var newText = document.createTextNode(myTextTwo);

newCell.appendChild(newText);
<table id="myList">
  <thead>
    <tr>
      <td>Product ID</td>
      <td>Product Name</td>
      <td>Quantity</td>
    </tr>
  </thead>
  <tbody>

  </tbody>
</table>

Comments