Link to home
Start Free TrialLog in
Avatar of submissiontechnology
submissiontechnology

asked on

Delete table row based on element ID

I have a dynamic table which has a number of rows like this:

<table id="wpt_tb">
<tbody>
<tr id="tb28791794">
<td>blah</td>
<td>blah</td>
</tr>
<tr id="tb28792890">
<td>blah</td>
<td>blah</td>
</tr>
</table>

I want to be able to remove 1 of the rows from the table
 I tried this code but it does not work:

var tb = document.getElementById("wpt_tb");
var rw = document.getElementById("tb28791794");
tb.removeChild(rw);

In Firefox it generates this error:
uncaught exception: [Exception... "Component returned failure code: 0x80004003 (NS_ERROR_INVALID_POINTER) [nsIDOMHTMLTableElement.removeChild]"  nsresult: "0x80004003"

In Internet Explorer it gives error "Invalid argument"

Please help! Thanks.
Avatar of HonorGod
HonorGod
Flag of United States of America image

This should help
<!doctype html public "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title> table rows </title>
<script type='text/javascript'>
  //------------------------------------------------------------------
  // Name: removeRow()
  // Role: delete the specified row from its associated table
  // Note: Parameter (obj) is a reference to any element within
  //      the row (e.g., an input field, or an anchor link)
  //------------------------------------------------------------------
  function removeRow( id ) {
    var tbl = document.getElementById( id );
    if ( tbl && tbl.nodeName == 'TABLE' ) {
      var trs = tbl.getElementsByTagName( 'tr' );
      if ( trs.length > 0 ) {
        var tr = trs[ 0 ];
        while ( tr.hasChildNodes() ) {
          tr.removeChild( tr.lastChild );
        }
        tr.parentNode.removeChild( tr );
      }
    }
  }
 
</script>
</head>
<body>
<div id='materials1'>
  <table id='tbl' border='1'>
    <tr>
      <td>One</td>
      <td>Two</td>
      <td>Three</td>
    </tr>
    <tr>
      <td>Four</td>
      <td>Five</td>
      <td>Six</td>
    </tr>
    <tr>
      <td>Seven</td>
      <td>Eight</td>
      <td>Nine</td>
    </tr>
    <tr>
      <td colspan='3' align='center'>
        <input type='button' onclick='removeRow("tbl")' value='removeRow'>
      </td>
    </tr>
  </table>
</div>
</body>
</html>

Open in new window

Avatar of submissiontechnology
submissiontechnology

ASKER

I tried that code and it didn't work either.

In Firefox it gave me this error:
Element referenced by ID/NAME in the global scope. Use W3C standard document.getElementById() instead.

In Internet Explorer it doesn't generate an error, but nothing happens and the row is still there.
What do you mean, you "tried that code"?
I just used the page that I provided, and ran it on IE 7.0.5730.11
and FireFox 2.0.0.11, and neither complained.

What code did you try?
Sorry, as written, the code expects the ID of the table to be supplied, and the first row is deleted.  One moment please...
ASKER CERTIFIED SOLUTION
Avatar of HonorGod
HonorGod
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Now in Firefox it gives error "tbl has no properties", and IE says "Object required".
This is the line generating the error: while ( tbl != document && tbl.nodeName != 'TABLE' ) {
By the way the row I'm deleting has been added previously with JavaScript, I'm not sure if that makes a difference?
Row is not the child of table directly but tbody. Try this way:

<html>
	<head>
		<title>Script Demo Gops&reg;</title>
		<script type="text/javascript" >
			window.onload=function(){
				var tb = document.getElementById("wpt_tb");
				var b=tb.getElementsByTagName('tbody')[0];
				var rw = document.getElementById("tb28791794");
				b.removeChild(rw);
			}
		</script>
	</head>
	<body>
		<table id="wpt_tb">
			<tbody>
				<tr id="tb28791794">
					<td>blah</td>
					<td>blah</td>
				</tr>
				<tr id="tb28792890">
					<td>blah</td>
					<td>blah</td>
				</tr>
			</tbody>
		</table>
 
	</body>
</html>

Open in new window

How about this?
<script type='text/javascript'>
  //------------------------------------------------------------------
  // Name: removeRow()
  // Role: delete the specified row from its associated table
  //------------------------------------------------------------------
  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 );
    }
  }
 
</script>

Open in new window

gops1, you are correct.
tr isn't a direct childof table.
Even if tbody isn't coded, it is implicit.

The purpose of the loop was to locate the row parent,
remove any children (i.e., cells)
then remove tr from its parent.
submissiontechnology

It would only matter if the table was not well formed.

If you happened to create a stand-alone tr element that was not in a "well formed" table structure, then the routine isn't written to handle that.  If you need it to do so, please let me know.
OK the latest code generates alert box with these messages...
IE: Specified document element is not found.  id=[object]
Firefox: Specified document element is not found.  id=[object HTMLTableRowElement]

This means it's some problem with my code adding the row?

Here's the code I'm using to add a row
function wpt_add() {
	var tbody = document.getElementById("wpt_tb").getElementsByTagName("TBODY")[0];
	var row = document.createElement("TR");
	var td1 = document.createElement("TD");
	var td2 = document.createElement("TD");
	var td3 = document.createElement("TD");
	
	var dt = new Date();
	var theid = "tb" + dt.getTime();
	
	row.setAttribute("id",theid);
	row.style.backgroundColor = '#ffffff';
	
	td1.innerHTML = document.getElementById("wpt_cb").value;
	td2.innerHTML = document.getElementById("wpt_info").value;
	td3.innerHTML = '<input type="button" value="Remove" onClick="wpt_remove(' + theid + ')">';
	
	row.appendChild(td1);
	row.appendChild(td2);
	row.appendChild(td3);
	
	document.getElementById("wpt_cb").value = '';
	document.getElementById("wpt_info").value = '';
	
	tbody.appendChild(row);
}

Open in new window

I found the problem. I didnt put the id in quotes (line 16 in above snippet)!
Thanks for your function HonorGod.
Excellent news.  Glad to hear that you have a solution that works for you.
Thanks for the grade/points.  Good luck, and Merry Christmas