Adding rows to table with button to remove

For adding a row, what I generally do is use a template with the row content. Add a button that when clicked, clones the template and adds the newly cloned row to the table.

Example:

<button id="addRowButton">
  Add a row
  <template>
    <tr>
      <td>New row</td>
      <td><button type="button" name="remove">Remove</button></td>
    </tr>
  </template>
</button>

JavaScript:

  const table = document.getElementById('theTable');
  const addButton = document.getElementById('addRowButton');
  addButton.addEventListener('click', (e)=>{
  	const newRow = addButton.querySelector('template').content.cloneNode(true);
   	table.appendChild(newRow);
  });
3 Likes