Here's a description of how JavaScript removechild () deletes a node, as shown in the following detail:
In JavaScript, only one way to delete a node is provided: RemoveChild ().
The RemoveChild () method deletes a child node of the parent node.
Grammar:
Parent.removechild (Thisnode)
Parameter description:
Parameters |
Description |
Thisnode |
The current node, which is the node to be deleted |
Parent |
The parent node of the current node, that is, the Thisnode.parentnode |
For example, the statement that deletes the node for id= "Demo" is:
var Thisnode=document.getelementbyid ("demo");
ThisNode.parentNode.removeNode (Thisnode);
For example, delete a node:
<div id= "Demo" >
<div id= "Thisnode" > Click Delete I </div>
</div>
<script type= "text/ JavaScript ">
document.getElementById (" Thisnode "). Onclick=function () {
This.parentNode.removeChild ( this);
}
</script>
Example Demo:
As you can see, JavaScript only provides a way to delete nodes, but it's enough.
Ps:javascript method for deleting child nodes
The HTML code is as follows:
<div id= "F" >
<div>a</div>
<div>b</div>
<div>c</div>
If you want to delete all the child nodes under the F node, it is natural and normal to think of the method should be the following code:
var f = document.getElementById ("f");
var childs = f.childnodes;
for (var i = 0; i < childs.length i++) {
alert (childs[i].nodename);
F.removechild (Childs[i]);
When the program is running, we find that no matter in Firefox or under IE, can not completely delete all the child nodes (Firefox in the blank area is also
As a node, so the result of the delete node will be different, because when you delete the child node with index 0, the original index is natural.
For the 1 node at this time its index to become 0, and then the variable i has become 1, the program continues to go away will delete the original index of 2 of the node now 1, so that the result of the program is to delete only half of the child nodes, the result is the same as in the traversal. Want to remove all nodes as normal
, we should remove it from the back, the code is as follows:
for (var i = childs.length-1 i >= 0; i--) {
alert (childs[i].nodename);
F.removechild (Childs[i]);
We start by deleting the maximum index and using the descending method so that the index doesn't move and change.