JS removechild and removenode

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.