Please note, this is a STATIC archive of website developer.mozilla.org from November 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

我們的志工尚未將此文章翻譯為 正體中文 (繁體) 版本。加入我們,幫忙翻譯!

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

文件標籤與貢獻者

標籤: 
 最近更新: fscholz,