0

I get confused about the parentNode in JS.Here is my code.

<table border="1" width="50%" id="table">
   <tr>
    <th>id</th>
    <th>name</th>
    <th>del</th>
   </tr>  

   <tr>
    <td>001</td>
    <td>Kevin</td>
    <td><a href="javascript:;" onclick="del(this);">del</a></td>   
   </tr>

and the JS code:

function del(obj){
     var tr = obj.parentNode.parentNode;
     tr.parentNode.removeChild(tr)
 }

the code works and I think the obj refers to the <a> tag, the obj.parentNode refers to the <td>tag, the obj.parentNode.parentNode refers to the <tbody>tag. so the tr.parentNode.removeChild(tr) means to remove the <tr>tag. Am I right?

the question is that if I change the code like this. It does not work.

function del(obj){
     var tr = obj.parentNode.parentNode.parentNode;
     tr.removeChild(tr)
 }
kevin su
  • 67
  • 7

3 Answers3

1

The reason why

tr.removeChild(tr)

doesn't work is because tr is not a child of tr, i.e. itself. However, tr.parentNode.removeChild(tr) works because tr is obviously a child of tr.parentNode.

dfsq
  • 191,768
  • 25
  • 236
  • 258
  • thanks there! can I ask another question? if I want to use `del()` instead of `del(this)` (not very clear know about the "this",I am a beginner) how can I change the `function()`? – kevin su Apr 28 '16 at 16:58
  • If you don't pass `this` inside del like `del(this)` then inside of it you will have to find clicked TD somehow, not very convenient if TD doesn't have any class or id, etc, something to identify it with document.querySelector method for example. You could however use this `onclick="del.call(this)"` and inside of the function `this` will point to what `obj` is not. – dfsq Apr 28 '16 at 17:04
1

removeChild will look for a node within the node calling the function. In other words tr.removeChild is looking for tr inside of tr. Try this instead:

var tr = obj.parentNode.parentNode;
var trParent = tr.parentNode;
trParent.removeChild(tr);
Cameron637
  • 1,699
  • 13
  • 21
-1

I had to deal with the same issue, and the answer is confusing and counter intuitive. Well, it has its logic, but leads to non-trivial behaviours.

Essentially, when a node is removed from the DOM tree, it fires a blur event (and before a focusout event too).

So, when you call removeChild, the blur event is fired again, but this time link still has its parentNode defined, but link isn't among its parent's children anymore! (Yes, read this twice. Or more.)

Answer from Failed to execute 'removeChild' on 'Node'

Community
  • 1
  • 1
Arjun Bala
  • 287
  • 1
  • 8
  • That seems unrelated to the problem presented here. Also, simply copying an answer is not really tolerated here. – Felix Kling Apr 28 '16 at 16:49