eabates
eabates

Reputation: 898

Traversing DOM in a table

I have an HTML table that has a delete button in each row of its last column. By clicking on one of these buttons, I would like to be able to delete the whole row in which it is situated. The follow code deletes the button itself but I am unable to get it to delete the whole row:

var bns = document.getElementsByTagName("button");
  for (var i = 0; i < bns.length; i++) {
    bns[i].addEventListener("click", function()
  {
   this.parentNode.parentNode.removeChild(this);    
  });
  }

My HTML looks like:

<body>
  <table class="table">
    <thead>
     <tr>
        <th>Students</th>
     </tr>
     <tr>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Email</th>
      <th>Delete</th>
    </tr>
  </thead>   
  <tbody>
    <tr>
      <td>John</td>
      <td>Doe</td>
      <td>[email protected]</td>
      <td><button>X</button></td>
    </tr> 

    <tr>
      <td>John</td>
      <td>Doe</td>
      <td>[email protected]</td>
      <td><button>X</button></td>
    </tr> 
</tbody>
</table>

Upvotes: 0

Views: 635

Answers (2)

brk
brk

Reputation: 50291

You can use HTMLTableElement.deleteRow()to delete a HTML table row. I have added an onclick event to each button and it will call deleteRow function which uses rowIndex & deleteRow().It do not require jquery to perform the action

HTML

<table class="table" id="table">
    <thead>
     <tr>
        <th>Students</th>
     </tr>
     <tr>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Email</th>
      <th>Delete</th>
    </tr>
  </thead>   
  <tbody>
    <tr>
      <td>John</td>
      <td>Doe</td>
      <td>[email protected]</td>
      <td><button onclick="deleteRow(this)">X</button></td>
    </tr> 

    <tr>
      <td>John</td>
      <td>Doe</td>
      <td>[email protected]</td>
      <td><button onclick="deleteRow(this)">X</button></td>
    </tr> 
</tbody>
</table>

JS

function deleteRow(r) {
    var i = r.parentNode.parentNode.rowIndex;
    document.getElementById("table").deleteRow(i);
}

DEMO HERE

Upvotes: 1

Doug McLean
Doug McLean

Reputation: 1309

I think it's the removeChild(this) that's the problem. That's being called on the <tr> but it's telling it to delete this which is the button.

Try:

var row = this.parentNode.parentNode;
row.parentNode.removeChild(row);

Alternatively with a framework such as jQuery it would be:

$(this).parent().parent().remove();

Edit

The complete jQuery code is actually nice and short, too:

$(document).ready(function(){
    $('button').click(function(){
        $(this).parents('tr').remove();
    });
});

Upvotes: 4

Related Questions