Node.firstChild
The Node.firstChild
read-only property returns the node's first child in the tree, or null
if the node is childless. If the node is a Document
, it returns the first node in the list of its direct children.
Syntax
var childNode = node.firstChild;
Description
childNode
is a reference to the first child of node
if there is one, otherwise it's null
.
Example
This example demonstrates the use of firstChild
and how whitespace nodes might interfere with using this property. See the Notes section for more information about whitespace handling in Gecko DOM.
<p id="para-01"> <span>First span</span> </p> <script type="text/javascript"> var p01 = document.getElementById('para-01'); alert(p01.firstChild.nodeName) </script>
In the above, the alert will show '#text' because a text node is inserted to maintain the whitespace between the end of the opening <p> and <span> tags. Any whitespace will cause the #text node to be inserted, from a single space to any number of spaces, returns, tabs, and so on.
Another #text node is inserted between the closing </span> and </p>tags.
If this whitespace is removed from the source, the #text nodes are not inserted and the span element becomes the paragraph's first child.
<p id="para-01"><span>First span</span></p> <script type="text/javascript"> var p01 = document.getElementById('para-01'); alert(p01.firstChild.nodeName) </script>
Now the alert will show 'SPAN'.
Specification
License
© 2016 Mozilla Contributors
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-us/docs/web/api/node/firstchild