CodeName
CodeName

Reputation: 579

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>

Upvotes: 0

Views: 149

Answers (2)

Turnip
Turnip

Reputation: 36652

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>

Upvotes: 2

Angel Politis
Angel Politis

Reputation: 11313

To make it work, you need to:

1) Put [0] after .getElementsByTagName() like below, as this method returns an array of elements, unlike .getElementById(), which returns the first instance:

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

2) Use the .insertCell() in the row you want the cell to be, in our case newRow, not on the table's tbody:

var newCell = newRow.insertCell(0);

Your correct JavaScript code should be:

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

You can also check out the following snippet:

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);
#myList {
  border: 1px solid black;
}
#empty {
  border-bottom: 1px solid black;
}
<table id = "myList">
  <thead>
    <tr>
      <td>Product ID</td>
      <td>Product Name</td>
      <td>Quantity</td>
    </tr>

     <!--- This row is for adding a border-bottom line -->
    <tr>
      <td id = "empty" colspan  ="3"></td>
    </tr>
  </thead>
  <tbody>
    
  </tbody>
</table>

Upvotes: 0

Related Questions