kevin su kevin su - 7 months ago 10
HTML Question

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

Answer

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.

Comments