Click the button below to change my parent's background color.
Prop Element Parentnode
## XML DOM parentNode Property
The `parentNode` property returns the parent node of the specified element or node in the DOM (Document Object Model) tree.
In XML and HTML documents, nodes are structured in a hierarchical tree. Every node (except the root node) has exactly one parent node. This property is highly useful for traversing upward through the DOM tree.
---
## Syntax and Usage
### Syntax
```javascript
node.parentNode
```
### Return Value
* **Node Object**: Returns the parent node of the current node.
* **null**: Returns `null` if the node has no parent (for example, if it is the `document` node itself or a newly created node that has not yet been inserted into the tree).
---
## Code Examples
### Example 1: Retrieving the Parent Node in XML
The following code snippet loads an XML document ([books.xml](/try/demo_source/books.xml)) using `loadXMLDoc()` and retrieves the parent node of the first `` element.
```javascript
// Load the XML document
xmlDoc = loadXMLDoc("books.xml");
// Get the first element
var childNode = xmlDoc.getElementsByTagName("title");
// Access its parent node
var parent = childNode.parentNode;
// Output the parent node's name
document.write("Parent node: " + parent.nodeName);
```
#### Output:
```text
Parent node: book
```
---
### Example 2: Traversing HTML DOM (Web Browser Environment)
In web development, you can use `parentNode` to dynamically manipulate HTML elements based on their hierarchy.
```html
```
---
## Considerations and Best Practices
### 1. `parentNode` vs. `parentElement`
While traversing the DOM, you may also encounter the `parentElement` property. Here is the key difference:
* **`parentNode`**: Returns any parent node, including `Document` and `DocumentFragment` nodes.
* **`parentElement`**: Only returns the parent if it is an **Element node** (node type 1). If the parent is not an element (such as the `#document` node), it returns `null`.
### 2. Document Node Parent
The top-most node in a document is the `document` node. Calling `parentNode` on the `document` node will always return `null`.
```javascript
console.log(document.parentNode); // Outputs: null
```
### 3. DocumentFragment Parent
Nodes inside a `DocumentFragment` will have their `parentNode` set to the fragment itself. Once the fragment is appended to the main DOM tree, their `parentNode` will update to the new target element.
YouTip