Method for Javascript to delete a specified element node

  • 2021-06-29 09:56:03
  • OfStack

When javascript operates on the dom tree, it may often encounter an increase, such as an increase button after an input box, a delete button, an increase input box by clicking on an increase, and a delete input box by clicking on a delete.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 one method in IE: removeNode(), try running the following code


<div><input onclick="removeNode(this)" type="text" value=" Click to remove the input box " /></div>

It can be found that this method works well with IE, but in standard browsers such as Firefox, the error will be removeNode is not defined, but in core JS, there is one way to operate on DOM nodes: removeChild(), if the name should tell you to remove the child node, then we can work through one to remove the specified node.We can first find the parent of the node to be deleted, then use removeChild in the parent 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 code below to execute it 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 the input box " /></div>

Related articles: