The removechild function can delete the specified child elements of the parent element.
If this function successfully deletes the child node, it returns the deleted node, otherwise it returns null.
Grammar structure:
fatherObj.removeChild(childrenObj)
Parameter explanation:
1.fatherObj: The element object of the child element to be deleted.
2.childrenObj: the child element object to be deleted.
Special instructions:
In Firefox, Google and browsers above IE8, blank space is also regarded as a text node, but in browsers below IE8 and IE8, blank text nodes will be ignored. For details, please refer to How to Get the Child Node and Parent Node of an Element in JavaScript chapter.
Code example:
Example 1:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="author" content="http://www.jb51.net/" /> <title>脚本之家</title> <script type="text/javascript"> window.onload=function(){ var obox=document.getElementById("box"); var lis=obox.getElementsByTagName("li"); obox.removeChild(lis[1]); } </script> </head> <body> <ul id="box"> <li>脚本之家一</li> <li>脚本之家二</li> <li>脚本之家三</li> <li>脚本之家四</li> </ul> </body> </html>
The above code can delete the second li element in the child element of box.
Example 2:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="author" content="http://www.softwhy.com/" /> <title>脚本之家</title> <script type="text/javascript"> window.onload=function(){ var obox=document.getElementById("box"); var liArray=[]; var y=0; var childNodes=obox.childNodes; for(var i=0;i<childNodes.length;i++){ if(childNodes[i].nodeType==1){ liArray[y]=childNodes[i]; y=y+1; } } obox.removeChild(liArray[1]); } </script> </head> <body> <ul id="box"> <li>脚本之家一</li> <li>脚本之家二</li> <li>脚本之家三</li> <li>脚本之家四</li> </ul> </body> </html>
The above code can select element nodes from all child nodes in the box, then put the element nodes into the array, and then delete the second element node.
Summary:
removeChild()
This function is to get the parent element of the element and delete it. The syntax is: parent.removeChild(child);
Sometimes we want to delete without touching the parent element. But DOM is this mechanism, and the element and parent element must be clear before deletion can be carried out. When entering the element to be deleted, we can also perform the deletion operation and use its parentNode attribute to find the parent element:
var child=document.getElementById(p1); child.parentNode.removeChild(child);
Note: jquery also has functions corresponding to removeChild: remove() and empty()
remove(): refers to deleting both itself and its sub-elements
empty(): deletes child elements