When you operate the DOM tree in Javascript, you may often encounter adding and deleting nodes. For example, you can add a button and delete a button after an input box and click Add to add an input box, click Delete to delete the corresponding input box. In some JS frameworks, such as prototype, you can use element. remove () to delete a node. The core JS does not have such a method. ie has such a method: removenode (), try to run the following code
<Div> <input onclick = "removenode (this)" type = "text" value = "click to remove this input box"/> </div> <br/>
Tip: you can modify some code before running it.
It can be found that this method is useful in IE, but the removenode is not defined error will be reported in Firefox and other standard browsers, however, in the core JS, there is a method to operate the DOM node: removechild (). You should know that the sub-node is removed by the name, then we can change it to remove the specified node. We can first find the parent node of the node to be deleted, and then use removechild in the parent node to remove the node we want to remove. We can define a method called removeelement.
123456 |
function removeElement(_element){ var _parentElement = _element.parentNode; if(_parentElement){ _parentElement.removeChild(_element); }} |
Try to run the following code, which can be correctly executed in various browsers.
<SCRIPT type = "text/JavaScript"> <br/> function removeelement (_ element) {<br/> VaR _ parentelement = _ element. parentnode; <br/> If (_ parentelement) {<br/> _ parentelement. removechild (_ element); <br/>}< br/> </SCRIPT> <br/> <div> <input onclick = "removeelement (this) "type =" text "value =" click to remove this input box "/> </div> <br/>
Tip: you can modify some code before running it.