pH7_JP1
pH7_JP1

Reputation: 3

parentNode is undefined for tr

When it reaches the line this.parentNode.removeChild(this);

I get the error

this.parentNode is undefined

In the debugger I pause at the beginning of that statement and see that "this" is: Object[ tr#CMD01.selected ] which is exactly what I expect. How is parentNode undefined? I have done a lot of searching for similar problems here and keep finding cases where "this" is not correct, but in my case it is verified by the debugger.

 $(document).ready(function() {
    	$.fn.deleteThisRow = function() {
    		this.parentNode.removeChild(this);
    	};
    });
    
    function deleteRow() {
    	$("#theList tr.selected").deleteThisRow();
    }
.selected {
		background-color: yellow
	}	
    <body>
    	<center id='bg'>
    	<table id="cmdList"> 
    		<thead>
    			<tr id="hdrow">
    				<th>Col1</th>
    				<th>Col2</th>
    				<th>Col3</th>
    			</tr>
    		</thead>
    		<tbody id="theList">
    			<tr id="CMD00">
    				<td>A1</td>
    				<td>A2</td>
    				<td>A3</td>
    			</tr>
    			<tr id="CMD01" class="selected">
    				<td>B1</td>
    				<td>B2</td>
    				<td>B3</td>
    			</tr>
    			<tr id="CMD02">
    				<td>C1</td>
    				<td>C2</td>
    				<td>C3</td>
    			</tr>
		</tbody>
	</table> 
	<table id="buttons">
		<tr>
			<td>
				<button onclick='deleteRow()'>Delete</button>
			</td>
		</tr>
	</table>
	</center>
    </body>

Upvotes: 0

Views: 464

Answers (1)

jfriend00
jfriend00

Reputation: 707796

When you implement a jQuery method, the value of this when it is called will be the jQuery object, not the DOM object. So, this.parentNode does not exist because a jQuery object does not have a property by that name.

You can either use jQuery's .parent() or you can get the actual DOM node and then use .parentNode on that.

If you only intend on ever processing a single DOM object at a time, you can do this:

$.fn.deleteThisRow = function() {
    this[0].parentNode.removeChild(this[0]);
};

If your jQuery object may have multiple objects in it, then you can do this:

$.fn.deleteThisRow = function() {
    this.remove();
};

Or, as you may notice, you don't even need a custom method for this. If you have a jQuery object for the row, you can just call .remove() on it directly.

function deleteRow() {
    $("#theList tr.selected").remove();
}

Upvotes: 4

Related Questions