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) } 
1
  • 1
    A node (tr) cannot be the a child of itself (tr) (unless time travel). Commented Apr 28, 2016 at 16:48

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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()?
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.
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); 

Comments

-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'

1 Comment

That seems unrelated to the problem presented here. Also, simply copying an answer is not really tolerated here.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.