When operating the dom tree in JavaScript, you may often encounter the addition and deletion of nodes, such as an input box with an addition button and a delete button. Click to add to add an input box, and click to delete to delete the corresponding input box. In some js frameworks, such as Prototype, you can use element.remove() to delete a node. There is no such method in core JS. There is a method in IE: removeNode(), try to run the following code
<div><input onclick="removeNode(this)" type="text" value="Click to remove this input box" /></div>
It can be found that this method works well in IE, but in standard browsers such as Firefox, removeNode is not defined. However, there is a method for operating DOM nodes in core JS: removeChild(). You should know that it is to remove the child node by looking at the name. Then we can adapt to the removal of the specified node. We can first find the parent node of the node to delete, and then use removeChild in the parent node to remove the node we want to remove. We can define a method called removeElement.
function removeElement(_element){ var _parentElement = _element.parentNode; if(_parentElement){ _parentElement.removeChild(_element); }}Try running the following code and it can be executed correctly in various browsers.
<script type="text/javascript">function removeElement(_element){ var _parentElement = _element.parentNode; if(_parentElement){ _parentElement.removeChild(_element); }}</script><div><input onclick="removeElement(this)" type="text" value="Click to remove this input box" /></div>The above is the entire content of this article. For more information about JavaScript, you can check out: "JavaScript Reference Tutorial" and "JavaScript Code Style Guide". I also hope that everyone will support Wulin.com more.