Search code examples
javascripthtmlinnerhtml

Html add and delete rows dynamically with javascript


I want to have a table with no rows initially and after that to create each row dynamically and also to be able to delete every row. I got Cannot read property 'childNodes' of undefined Please let me know how it should be done, Thank you.

function addRow() {
  var table = document.getElementById("myTable");
  var row = table.insertRow(0);
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);
  cell1.innerHTML = "NEW CELL1";
  cell2.innerHTML = "NEW CELL2";
}

function deleteRow(tableID) {
  try {
    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;

    for (var i = 0; i < rowCount; i++) {
      var row = table.rows[i];
      var chkbox = row.cells[0].childNodes[0];

      table.deleteRow(i);
      rowCount--;
      i--;
    }
  } catch (e) {
    alert(e);
  }
}
<!DOCTYPE html>
<html>

<head>
  <style>
    table,
    td {
      border: 1px solid black;
    }
  </style>
</head>

<body>

  <p>Click the button to add a new row at the first position of the table and then add cells and content.</p>

  <table id="myTable">
    <TR>

    </TR>
  </table>
  <br>

  <button type="button" onclick="addRow()">Add</button>
  <button type="button" onclick="deleteRow('myTable')">Delete</button>

</body>

</html>


Solution

  • You can achieve it by simply changing your deleteRow() function like below. Whereas row.cells[0].childNodes[0] gives you error. row.cells[0] gives you HTML code, similar to like this - <td>NEW CELL1</td>. The childNode of that HTML does not have any information. So, always throws an error.

    function addRow() {
      var table = document.getElementById("myTable");
      var row = table.insertRow(0);
      var cell1 = row.insertCell(0);
      var cell2 = row.insertCell(1);
      cell1.innerHTML = "NEW CELL1";
      cell2.innerHTML = "NEW CELL2";
    }
    
    function deleteRow(tableID) {
      document.getElementById(tableID).innerHTML = "";
    }
    <!DOCTYPE html>
    <html>
    
    <head>
      <style>
        table,
        td {
          border: 1px solid black;
        }
      </style>
    </head>
    
    <body>
    
      <p>Click the button to add a new row at the first position of the table and then add cells and content.</p>
    
      <table id="myTable">
        <tr>
    
        </tr>
      </table>
      <br>
    
      <button type="button" onclick="addRow()">Add</button>
      <button type="button" onclick="deleteRow('myTable')">Delete</button>
    
    </body>
    </html>