Element.firstElementChild

ParentNode.firstElementChild 只读属性,返回对象的第一个子 元素, 如果没有子元素,则为null。

他的属性最初是在element遍历纯接口中定义的。由于这个接口包含两组不同的属性,一个针对具有子元素的Node,一个针对子元素的属性,因此它们被移动到两个单独的纯接口中,ParentNodeChildNode。在本例中,firstElementChild移动到ParentNode。这是一个相当技术性的更改,不应该影响兼容性。

语法

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>

适用于 IE8、IE9 和 Safari 的 Polyfill

// Overwrites native 'firstElementChild' prototype.
// Adds Document & DocumentFragment support for IE9 & Safari.
// Returns array instead of HTMLCollection.
;(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);

规范

Specification Status Comment
DOM
ParentNode.firstElementChild
Living Standard Splitted the ElementTraversalinterface in ChildNode and ParentNode. This method is now defined on the latter.
The Document and DocumentFragment implemented the new interfaces.
Element Traversal Specification
ElementTraversal.firstElementChild
Obsolete Added its initial definition to theElementTraversal pure interface and use it on Element.

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
firstElementChildChrome Full support 1Edge ? Firefox Full support 3.5IE Full support 9Opera Full support 10Safari Full support 4WebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes
Support on Document and DocumentFragment
Experimental
Chrome Full support 29Edge ? Firefox Full support 25IE No support NoOpera Full support 16Safari No support NoWebView Android Full support YesChrome Android Full support YesFirefox Android ? Opera Android ? Safari iOS No support NoSamsung Internet Android Full support Yes

Legend

Full support  
Full support
No support  
No support
Compatibility unknown  
Compatibility unknown
Experimental. Expect behavior to change in the future.
Experimental. Expect behavior to change in the future.

参见

Ed