Met Element 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
parentElement.removeChild(node)
```
### Parameters
| Parameter | Type | Required / Optional | Description |
| :--- | :--- | :--- | :--- |
| `node` | Node Object | **Required** | The child node you want to remove from the parent element. |
### Return Value
* **Node Object**: Returns the removed node if successful. This node is still kept in memory and can be reinserted into the DOM 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 element).
---
## Code Examples
### Example 1: Removing a Specific Child Node
The following code snippet loads the XML document `books.xml` and removes the first `` element from the root element:
```javascript
// Load the XML document
var xmlDoc = loadXMLDoc("books.xml");
// Get the first element
var targetNode = xmlDoc.getElementsByTagName("book");
// Remove the target node from the root element
var removedNode = xmlDoc.documentElement.removeChild(targetNode);
// Output the name of the removed node
document.write("Removed node: " + removedNode.nodeName);
```
**Output:**
```text
Removed node: book
```
---
### Example 2: Dynamically Removing the Last Child Node
This example demonstrates how to target and remove the last child node of a specific parent element dynamically:
```javascript
var xmlDoc = loadXMLDoc("books.xml");
// Get the first element
var parentNode = xmlDoc.getElementsByTagName("book");
// Find its last child node
var lastChild = parentNode.lastChild;
// Remove the last child node
if (lastChild) {
var removed = parentNode.removeChild(lastChild);
console.log("Successfully removed: " + removed.nodeName);
}
```
---
## Key Considerations
1. **Parent-Child Relationship**: The node passed as an argument to `removeChild()` must be a direct child of the calling element. If you attempt to remove a node that is not a child of the parent, the browser will throw a `NotFoundError` DOM exception.
2. **Safe Removal Pattern**: To safely remove a node without explicitly knowing its parent, you can use the `parentNode` property:
```javascript
var nodeToRemove = document.getElementById("my-element");
if (nodeToRemove && nodeToRemove.parentNode) {
nodeToRemove.parentNode.removeChild(nodeToRemove);
}
```
3. **Memory Retention**: The removed node is not immediately destroyed. It remains in memory as an orphaned node. You can re-insert it back into the document at a different location using methods like `appendChild()` or `insertBefore()`. If you do not store the returned node in a variable, it will eventually be cleared by garbage collection.
YouTip