Search code examples
javascripthtmlrow

How to delete a table row using a delete button that has been assigned to each row?


I have a table with a button that adds rows to the table:

var addBtn = document.getElementById("btn");
addBtn.onclick = addToTable;

function addToTable() {
  var webdevtable = document.getElementById("webdevtable");
  var webdevrow = webdevtable.insertRow(-1);
  var webdevcell1 = webdevrow.insertCell(0);
  var webdevcell2 = webdevrow.insertCell(1);

  var webdevRowNum = webdevtable.rows.length - 1;
  webdevcell1.innerHTML = webdevRowNum;
  webdevcell2.innerHTML = "<button id='deleteRow" + webdevRowNum + "'>Delete This Row</button>";

  var delbtnid = "deleteRow" + webdevRowNum;
  var delbtn = document.getElementById(delbtnid);

  delbtn.onclick = function() {
    webdevtable.deleteRow(webdevRowNum);
  }
}
<button id="btn">Add row</button>

<table id="webdevtable">
  <tr>
    <th>Row No.</th>
  </tr>
</table>

When the "Add row" button is clicked, it adds a new row to the table with a "Delete This Row" button. The "Delete This Row" button for each row is given an id according to its row number.

E.g. the "Delete This Row" button for the first row has an id = "deleteRow1". For row 2, that button will have an id = "deleteRow2" etc.

Clicking on the delete button for that row is supposed to delete that row. The problem is that deleting a row changes the number of rows in the table so that the delete button sometimes doesn't target the correct row.

What logic can I add to the delete row function that makes it target the correct row every time?


Solution

  • Without using IDs:

    delbtn.onclick = function(e){
      let clickedButton = e.target;
      clickedButton.closest("tr").remove();
    }