YouTip LogoYouTip

Dom Met Node Appendchild

## XML DOM appendChild() Method The `appendChild()` method is a fundamental part of the XML DOM (Document Object Model). It allows developers to append a new child node to the end of the list of children of a specified parent node. --- ## Definition and Usage The `appendChild()` method adds a node to the end of the list of children of a specified parent node. ### Key Features: * **Node Insertion:** If the node to be appended already exists in the document tree, `appendChild()` automatically moves it from its current position to the new position (there is no need to manually remove the node from its parent first). * **Return Value:** The method returns the newly appended `Node` object. --- ## Syntax ```javascript parentNode.appendChild(newChild); ``` ### Parameters | Parameter | Type | Description | | :--- | :--- | :--- | | `newChild` | `Node` | **Required.** The node object you want to append to the end of the parent node's children. | ### Return Value | Type | Description | | :--- | :--- | | `Node` | Returns the appended child node (`newChild`). | --- ## Code Examples ### Example 1: Creating and Appending a New Element The following code snippet uses `loadXMLDoc()` to load the XML file [books.xml](/try/demo_source/books.xml) into `xmlDoc`. It then creates a new element node (``) and appends it to the end of the first `` element. ```javascript // Load the XML document var xmlDoc = loadXMLDoc("books.xml"); // Create a new element node named "edition" var newElement = xmlDoc.createElement("edition"); // Target the first element var bookNode = xmlDoc.getElementsByTagName("book"); // Append the new element to the element bookNode.appendChild(newElement); // Output the node name of the newly appended element to verify document.write(bookNode.getElementsByTagName("edition").nodeName); ``` #### Output: ```text edition ``` --- ## Important Considerations 1. **Moving Existing Nodes:** If `newChild` is already present in the DOM tree, `appendChild()` will move it from its current position to the new target position. It does not clone the node. 2. **Document Fragments:** If you append a `DocumentFragment`, the entire contents of the fragment are moved into the child list of the target parent node, leaving the fragment empty. 3. **Hierarchy Errors:** A `DOMException` will be thrown if: * The `newChild` is an ancestor of the parent node. * You attempt to append a node type that cannot be a child of the parent (e.g., appending an element directly to an attribute node).
← Dom Met Node ClonenodeDom Prop Node Textcontent β†’