ParentNode.firstElementChild read-only property returns the object's first child 元素 ,或 null if there are no child elements.

This property was initially defined in the ElementTraversal pure interface. As this interface contained two distinct set of properties, one aimed at 节点 that have children, one at those that are children, they have been moved into two separate pure interfaces, ParentNode and ChildNode 。在此情况下, firstElementChild moved to ParentNode . This is a fairly technical change that shouldn't affect compatibility.

句法

var element = node.firstElementChild;
					

范例

<ul id="foo">
  <li>First  (1)</li>
  <li>Second (2)</li>
  <li>Third  (3)</li>
</ul>
<script>
var foo = document.getElementById('foo');
// yields: First  (1)
console.log(foo.firstElementChild.textContent);
</script>
					

Polyfill for IE8, IE9 and Safari

// Overwrites native 'firstElementChild' prototype.
// Adds Document & DocumentFragment support for IE9 & Safari.
;(function(constructor) {
    if (constructor &&
        constructor.prototype &&
        constructor.prototype.firstElementChild == null) {
        Object.defineProperty(constructor.prototype, 'firstElementChild', {
            get: function() {
                var node, nodes = this.childNodes, i = 0;
                while (node = nodes[i++]) {
                    if (node.nodeType === 1) {
                        return node;
                    }
                }
                return null;
            }
        });
    }
})(window.Node || window.Element);
					

规范

规范 状态 注释
DOM
The definition of 'ParentNode.firstElementChild' in that specification.
实时标准 Split the ElementTraversal interface in ChildNode and ParentNode . This method is now defined on the latter.
Document and DocumentFragment implemented the new interfaces.
Element Traversal Specification
The definition of 'ElementTraversal.firstElementChild' in that specification.
过时 Added its initial definition to the ElementTraversal pure interface and use it on 元素 .

浏览器兼容性

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
firstElementChild Chrome 1 Edge 12 Firefox 3.5 IE 9 Opera 10 Safari 4 WebView Android Yes Chrome Android Yes Firefox Android 4 Opera Android Yes Safari iOS Yes Samsung Internet Android Yes
Support on Document and DocumentFragment Chrome 29 Edge ≤79 Firefox 25 IE No Opera 16 Safari No WebView Android Yes Chrome Android Yes Firefox Android ? Opera Android ? Safari iOS No Samsung Internet Android Yes

图例

完整支持

完整支持

不支持

不支持

兼容性未知 ?

兼容性未知

实验。期望将来行为有所改变。

实验。期望将来行为有所改变。

另请参阅

元数据

  • 最后修改: