Node.firstChild read-only property returns the node's first child in the tree, or null if the node has no children. 若节点是 Document , it returns the first node in the list of its direct children.

句法

var childNode = node.firstChild;
					

范例

This example demonstrates the use of firstChild and how whitespace nodes might interfere with using this property.

<p id="para-01">
  <span>First span</span>
</p>
<script>
  var p01 = document.getElementById('para-01');
  console.log(p01.firstChild.nodeName);
</script>
					

In the above, the console will show '#text' because a text node is inserted to maintain the whitespace between the end of the opening <p> and <span> 标签。 任何 whitespace 将创建 #text node, from a single space to multiple spaces, returns, tabs, and so on.

Another #text node is inserted between the closing </span> and </p> 标签。

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>
  var p01 = document.getElementById('para-01');
  console.log(p01.firstChild.nodeName);
</script>
					

Now the console will show 'SPAN'.

To avoid the issue with node.firstChild 返回 #text or #comment nodes, ParentNode.firstElementChild can be used to return only the first element node. However, node.firstElementChild requires a shim for Internet Explorer 9 and earlier.

规范

规范 状态 注释
DOM
The definition of 'Node.firstChild' in that specification.
实时标准 无变化
DOM (文档对象模型) 3 级核心规范
The definition of 'Node.firstChild' in that specification.
过时 无变化
DOM (文档对象模型) 级别 2 核心规范
The definition of 'Node.firstChild' in that specification.
过时 无变化
DOM (文档对象模型) 1 级规范
The definition of 'Node.firstChild' in that specification.
过时 初始定义

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
firstChild Chrome Yes Edge 12 Firefox 1 IE Yes Opera Yes Safari Yes WebView Android Yes Chrome Android Yes Firefox Android 4 Opera Android Yes Safari iOS Yes Samsung Internet Android Yes

图例

完整支持

完整支持

元数据

  • 最后修改: