Delete a row from a table by id

112,488

Solution 1

How about:

function deleteRow(rowid)  
{   
    var row = document.getElementById(rowid);
    row.parentNode.removeChild(row);
}

And, if that fails, this should really work:

function deleteRow(rowid)  
{   
    var row = document.getElementById(rowid);
    var table = row.parentNode;
    while ( table && table.tagName != 'TABLE' )
        table = table.parentNode;
    if ( !table )
        return;
    table.deleteRow(row.rowIndex);
}

Solution 2

And what about trying not to delete but hide that row?

Solution 3

From this post, try this javascript:

function removeRow(id) {
  var tr = document.getElementById(id);
  if (tr) {
    if (tr.nodeName == 'TR') {
      var tbl = tr; // Look up the hierarchy for TABLE
      while (tbl != document && tbl.nodeName != 'TABLE') {
        tbl = tbl.parentNode;
      }

      if (tbl && tbl.nodeName == 'TABLE') {
        while (tr.hasChildNodes()) {
          tr.removeChild( tr.lastChild );
        }
      tr.parentNode.removeChild( tr );
      }
    } else {
      alert( 'Specified document element is not a TR. id=' + id );
    }
  } else {
    alert( 'Specified document element is not found. id=' + id );
  }
}

I tried this javascript in a test page and it worked for me in Firefox.

Solution 4

to Vilx-:

var table = row.parentNode;
while ( table && table.tagName != 'TABLE' )
    table = table.parentNode;

and what if row.parentNode is TBODY?

You should check it out first, and after that do while by .tBodies, probably

Solution 5

Something quick and dirty:

<script type='text/javascript'>
function del_tr(remtr)  
{   
    while((remtr.nodeName.toLowerCase())!='tr')
        remtr = remtr.parentNode;

    remtr.parentNode.removeChild(remtr);
}
function del_id(id)  
{   
        del_tr(document.getElementById(id));
}
</script>

if you place

<a href='' onclick='del_tr(this);return false;'>x</a>

anywhere within the row you want to delete, than its even working without any ids

Share:
112,488
zozo
Author by

zozo

Same old me.

Updated on April 02, 2020

Comments

  • zozo
    zozo about 4 years

    I have a little problem. I have some dynamically created tables and each row has an id. I want to delete the row with the id "x".

    I tried the usual method (removeChild) but it doesn't work for tables apparently.

    function deleteRow(tableid, rowid)  
    {   
          document.getElementById(tableid).removeChild(document.getElementById(rowid));  
    }   
    

    The error I get is: Node was not found" code: "8

    I also tried this:

    function deleteRow(tbodyid, rowid)   
    {  
          document.getElementById(tbodyid).removeChild(document.getElementById(rowid));   
    }   
    

    and got the same error.

    I can't use the deleteRow() method because that one needs the index of the row and I prefer not to search for the id mark the index then delete (even though if I don't find other solutions...).