ParentNode.firstElementChild
只读属性,返回对象的第一个子 元素
, 如果没有子元素,则为null。
他的属性最初是在element遍历
纯接口中定义的。由于这个接口包含两组不同的属性,一个针对具有子元素的Node
,一个针对子元素的属性,因此它们被移动到两个单独的纯接口中,ParentNode
和ChildNode
。在本例中,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 ElementTraversal interface 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 . |
浏览器兼容性
BCD tables only load in the browser
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.
参见
Ed
- 纯接口
ParentNode
和ChildNode
。