--- title: ParentNode.firstElementChild slug: orphaned/Web/API/ParentNode/firstElementChild translation_of: Web/API/ParentNode/firstElementChild original_slug: Web/API/ParentNode/firstElementChild ---
{{ APIRef("DOM") }}
ParentNode.firstElementChild 介面會會返回 ParentNode的第一個子元素(唯讀) ,如果該節點沒有子節點則返回null。
This property was initially defined in the {{domxref("ElementTraversal")}} pure interface. As this interface contained two distinct set of properties, one aimed at {{domxref("Node")}} that have children, one at those that are children, they have been moved into two separate pure interfaces, {{domxref("ParentNode")}} and {{domxref("ChildNode")}}. In this case, firstElementChild moved to {{domxref("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>
// 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);
| Specification | Status | Comment |
|---|---|---|
| {{SpecName('DOM WHATWG', '#dom-parentnode-firstelementchild', 'ParentNode.firstElementChild')}} | {{Spec2('DOM WHATWG')}} | Split the ElementTraversal interface in {{domxref("ChildNode")}} and ParentNode. This method is now defined on the latter.The {{domxref("Document")}} and {{domxref("DocumentFragment")}} implemented the new interfaces. |
| {{SpecName('Element Traversal', '#attribute-firstElementChild', 'ElementTraversal.firstElementChild')}} | {{Spec2('Element Traversal')}} | Added its initial definition to the ElementTraversal pure interface and use it on {{domxref("Element")}}. |
{{Compat("api.ParentNode.firstElementChild")}}