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

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

语法

var element = node.firstElementChild;
var childNode = elementNodeReference.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.
// 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.

浏览器兼容性

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (on Element) 1.0 3.5 (1.9.1) 9.0 10.0 4.0
Support on Document and DocumentFragment 29.0 25.0 (25.0) 未实现 16.0 未实现
Feature Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (on Element) (Yes) 1.0 (1.9.1) (Yes) (Yes) (Yes)
Support on Document and DocumentFragment (Yes) 25.0 (25.0) 未实现 16.0 未实现

相关链接

文档标签和贡献者

 此页面的贡献者: xgqfrms-GitHub, teoli, AlexChao, ziyunfei
 最后编辑者: xgqfrms-GitHub,