Met Element Haschildnodes
## XML DOM hasChildNodes() Method
The `hasChildNodes()` method is a standard DOM (Document Object Model) API used to determine whether a specific element node contains any child nodes. It returns a boolean value (`true` or `false`) based on the presence of child nodes.
---
## Definition and Usage
The `hasChildNodes()` method returns `true` if the selected element node has one or more child nodes. Otherwise, it returns `false`.
### What counts as a child node?
In the XML DOM, child nodes are not limited to element nodes (like ``). They also include:
* **Element nodes** (HTML/XML tags)
* **Text nodes** (including whitespace, line breaks, and text content inside tags)
* **Attribute nodes** (though they are not considered children of an element in standard traversal, they exist in the DOM)
* **Comment nodes**
If an element contains even a single space or a line break between its opening and closing tags, `hasChildNodes()` will return `true` because that whitespace is parsed as a text node.
---
## Syntax
```javascript
elementNode.hasChildNodes()
```
### Return Value
* **`true`**: The element contains at least one child node.
* **`false`**: The element contains no child nodes.
---
## Code Example
The following code snippet loads an XML document named [books.xml](/try/demo_source/books.xml) using the `loadXMLDoc()` helper function and checks if the first `` element contains any child nodes.
```javascript
// Load the XML document
xmlDoc = loadXMLDoc("books.xml");
// Get the first element
var x = xmlDoc.getElementsByTagName("book");
// Check if it has child nodes and write the result
document.write(x.hasChildNodes());
```
### Output
```text
true
```
---
## Practical Considerations
### 1. Whitespace and Text Nodes
One of the most common pitfalls when using `hasChildNodes()` is unexpected whitespace. Consider the following XML snippets:
**Case A (Empty Element):**
```xml
```
* `hasChildNodes()` returns **`false`** because there is absolutely nothing between the tags.
**Case B (Whitespace/Formatting):**
```xml
```
* `hasChildNodes()` returns **`true`** because the line break and spaces between `` and ` ` are parsed as a text node.
### 2. Checking for Element Children Only
If you want to check if an element contains other **element nodes** (ignoring text and comment nodes), you should check the `childElementCount` property or filter the `children` collection:
```javascript
// Check if there are actual element children (ignores whitespace/text nodes)
if (elementNode.childElementCount > 0) {
// The element has child elements
}
```
YouTip