Visit Mozilla.org

DOM:element.firstChild

From MDC

(Redirected from firstChild)

« Gecko DOM Reference

Contents

[edit] Summary

Returns the node's first child in the tree, or null if the node is childless.

[edit] Syntax

childNode = node.firstChild;

childNode is a reference to the first child of node if there is one, otherwise it's null.

[edit] 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'.

[edit] Notes

Gecko-based browsers insert text nodes into a document to represent whitespace in the source markup. Therefore a node obtained for example via firstChild or previousSibling may refer to a whitespace text node, rather than the actual element the author intended to get.

See Whitespace in the DOM and W3C DOM 3 FAQ: Why are some Text nodes empty? for more information.

Sometimes document.firstChild is used to obtain the root element of a document. This is incorrect, as it will return a processing instruction or another node from the prolog if there are any, document.documentElement should be used instead.

[edit] Specification

DOM Level 1 Core: firstChild

DOM Level 2 Core: firstChild