kevin su
kevin su

Reputation: 67

confuse about the parentNode

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)
 }

Upvotes: 0

Views: 77

Answers (3)

Arjun Bala
Arjun Bala

Reputation: 287

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'

Upvotes: -1

Cameron637
Cameron637

Reputation: 1719

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);

Upvotes: 1

dfsq
dfsq

Reputation: 193301

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.

Upvotes: 1

Related Questions