`)
* **Text Node**: `nodeType` is `3` (e.g., text content, whitespace)
### Modern Alternative: `firstElementChild`
If you only want to retrieve the first **element** node (ignoring text and comment nodes), you should use the modern `firstElementChild` property:
```javascript
var firstElement = nodeObject.firstElementChild;
```
---
## Code Examples
### Example 1: Cross-Browser Safe Retrieval of the First Element Node
The following example loads an XML file (`books.xml`) and uses a custom helper function to safely retrieve the first child node that is an **element node** (where `nodeType` is `1`), bypassing any whitespace text nodes.
```javascript
// Helper function to get the first child element node
function get_firstchild(n) {
var x = n.firstChild;
// Loop until we find a node with nodeType 1 (Element Node)
while (x && x.nodeType !== 1) {
x = x.nextSibling;
}
return x;
}
// Load the XML document
var xmlDoc = loadXMLDoc("books.xml");
// Retrieve the first child element of the document
var firstChildElement = get_firstchild(xmlDoc);
// Output the node name and type
console.log("Node Name: " + firstChildElement.nodeName); // Output: bookstore
console.log("Node Type: " + firstChildElement.nodeType); // Output: 1
```
**Expected Output:**
```text
Node Name: bookstore
Node Type: 1
```
---
### Example 2: HTML DOM Implementation
Here is how `firstChild` behaves in an HTML document when whitespace is present.
```html
```
---
## Related Properties
* **`lastChild`**: Returns the last child node of a specified node.
* **`childNodes`**: Returns a collection of a node's child nodes (including text and comment nodes).
* **`nextSibling`**: Returns the node immediately following the specified node in the same tree level.
First Paragraph
Second Paragraph
YouTip