1

I want to effectively simulate pressing the "delete" button and remove the elements. I can do it with "deleteRow", but I want to specifically target the button "delete" to do this in the DOM specifically. This is about automating the press via the DOM. Table example is from W3*.

HTML

 <table id="mytab1">
<tr>
   <td>Row 1</td>
   <td><input type="button" value="Delete" onclick="deleteRow(this)"></td>
</tr>
<tr>
   <td>Row 2</td>
   <td><input type="button" value="Delete" onclick="deleteRow(this)"></td>
</tr>
<tr>
   <td>Row 3</td>
   <td><input type="button" value="Delete" onclick="deleteRow(this)"></td>
</tr>
  </table>

Javscript

for(var i = 0; i < 3; i++){
         var x = document.getElementById("mytab1").deleteRow('tr');

 }

Thank you in advance.

mike_f
  • 23
  • 6

2 Answers2

0

Your function should look like :

function deleteRow(self) {
    self.parentNode.parentNode.remove();
}

var buttons = document.querySelectorAll("#mytab1 input");
for (var i = 0; i <= buttons.length; i++) {
    buttons[i].click();
}

Test Snippet:

function deleteRow(self) {
  self.parentNode.parentNode.remove();
}

var buttons = document.querySelectorAll("#mytab1 input");
for (var i = 0; i < buttons.length; i++) {
  setTimeout(function(i) {
    buttons[i].click();
  }, 500 * i, i);
}
<table id="mytab1">
  <tr>
    <td>Row 1</td>
    <td><input type="button" value="Delete" onclick="deleteRow(this)"></td>
  </tr>
  <tr>
    <td>Row 2</td>
    <td><input type="button" value="Delete" onclick="deleteRow(this)"></td>
  </tr>
  <tr>
    <td>Row 3</td>
    <td><input type="button" value="Delete" onclick="deleteRow(this)"></td>
  </tr>
</table>
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
0

When looping over the elements you can simply use elements[i].click(), and trigger the deletion of the target row with .deleteRow(row), where row evaluates to an index (which gets passed through from the function call):

function deleteRow(row) {
    var i = row.parentNode.parentNode.rowIndex;
    document.getElementById("mytab1").deleteRow(i);
}
const elements = document.getElementsByTagName('td');

for (let i = 0; i < elements.length; i++) {
  elements[i].click();
}
<table id="mytab1">
  <tr>
    <td>Row 1</td>
    <td><input type="button" value="Delete" onclick="deleteRow(this)"></td>
  </tr>
  <tr>
    <td>Row 2</td>
    <td><input type="button" value="Delete" onclick="deleteRow(this)"></td>
  </tr>
  <tr>
    <td>Row 3</td>
    <td><input type="button" value="Delete" onclick="deleteRow(this)"></td>
  </tr>
</table>
Obsidian Age
  • 41,205
  • 10
  • 48
  • 71