Appendchild and removechild If the parent nodes of the nodes to be operated are both body, then there is no need to obtain the body parent node in advance. Or if the parent node is not the body, it is necessary to obtain the parent node in advance before using it?
高洛峰2017-06-14 10:53:27
Similar to this
var _body = document.body;
_body.appendChild(document.createElement('h1'));
_body.removechild(docuemnt.getElementsByTagName('h1')[0]);
There is no such usage
appendChild(***).removeChild(***) //肯定报错
As for what you said, there is no need to obtain and operate the parent node of the body. The code does not know where to operate, and an error will definitely be reported.
天蓬老师2017-06-14 10:53:27
Node.removeChild() method removes a child node from the DOM. Return deleted nodes.
Grammar
let oldChild = node.removeChild(child);
//OR
element.removeChild(child);
child is the child node to be removed.
node is the parent node of child.
oldChild holds a reference to the deleted child node. oldChild === child.
It is recommended that you read: https://developer.mozilla.org...
Node.appendChild() method adds a node to the end of the child node list of the specified parent node.
var child = node.appendChild(child);
node is the parent node to insert the child node.
child is both the parameter and the return value of this method.
Example:
// 创建一个新的段落p元素,然后添加到body的最尾部
var p = document.createElement("p");
document.body.appendChild(p);
It is recommended that you read: https://developer.mozilla.org...
三叔2017-06-14 10:53:27
Be sure to get the parent element first before using appendChild(), otherwise how can you be sure it is added after that element. . . . . .
过去多啦不再A梦2017-06-14 10:53:27
The<body> tag also has parent nodes and sibling nodes of <head><html>, so it’s best to get the parent node
怪我咯2017-06-14 10:53:27
The parent node must be obtained in advance. The case is to use document.body directly. Get the parent node body. This is a specification established by DOM level 0. If the parent node is not body. Get it separately. Because other parent nodes are different from body.