YouTip LogoYouTip

Dom Met Node Removechild

## XML DOM removeChild() Method The `removeChild()` method removes a specified child node from the current element. If the operation is successful, the method returns the removed node as a Node object. If the operation fails, it returns `null`. --- ## Syntax ```javascript parentNode.removeChild(node) ``` ### Parameters | Parameter | Type | Required/Optional | Description | | :--- | :--- | :--- | :--- | | `node` | Node | **Required** | The child node object that you want to remove from the parent element. | ### Return Value * **Node**: Returns the removed node object if successful. The removed node still exists in memory, meaning it can be inserted elsewhere in the document later. * **null / Error**: Returns `null` or throws a DOM exception if the node cannot be removed (e.g., if the specified node is not a child of the parent node). --- ## Code Example The following code snippet loads the XML document [books.xml](/try/demo_source/books.xml) using `loadXMLDoc()` and removes the first `` element from the document root: ```javascript // Load the XML document xmlDoc = loadXMLDoc("books.xml"); // Get the first element y = xmlDoc.getElementsByTagName("book"); // Remove the element from the root element x = xmlDoc.documentElement.removeChild(y); // Output the name of the removed node document.write("Removed node: " + x.nodeName); ``` ### Output ```text Removed node: book ``` --- ## Important Considerations 1. **Parent-Child Relationship**: The `removeChild()` method must be called on the immediate parent node of the node you want to remove. If the node passed as an argument is not a child of the calling node, the browser will throw a `NotFoundError` DOM exception. 2. **Dynamic Node Removal**: If you want to remove an element but do not have a direct reference to its parent, you can use the `parentNode` property to dynamically target the parent: ```javascript var child = document.getElementById("my-child-element"); if (child && child.parentNode) { child.parentNode.removeChild(child); } ``` 3. **Memory Retention**: When a node is removed using `removeChild()`, it is detached from the active DOM tree but remains in memory. You can store it in a variable and re-insert it into the document later using methods like `appendChild()` or `insertBefore()`. If you want to destroy the node completely to free up memory, you should clear its references or let it go out of scope so that it can be garbage-collected. 4. **Modern Alternative**: In modern web development (HTML DOM), you can also use the simpler `element.remove()` method, which allows an element to remove itself directly without referencing its parent (e.g., `node.remove()`). However, `removeChild()` remains the standard for XML DOM manipulation and offers excellent backward compatibility.
← Dom Met Node ReplacechildMet Node Lookupprefix β†’