--- title: Element.lastElementChild slug: Web/API/Element/lastElementChild translation_of: Web/API/Element/lastElementChild tags: - API - DOM - Element - Property browser-compat: api.Element.lastElementChild ---
{{ APIRef("DOM") }}
只读属性 Element.lastElementChild 返回对象的最后一个子{{domxref("Element", "元素")}},如果没有子元素,则返回 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("Element")}} and {{domxref("ChildNode")}}. In this case, lastElementChild moved to {{domxref("Element")}}. This is a fairly technical change that shouldn't affect compatibility.
var element = node.lastElementChild;
<ul id="foo">
<li>First (1)</li>
<li>Second (2)</li>
<li>Third (3)</li>
</ul>
<script>
var foo = document.getElementById('foo');
// yields: Third (3)
console.log(foo.lastElementChild.textContent);
</script>
// Overwrites native 'lastElementChild' prototype.
// Adds Document & DocumentFragment support for IE9 & Safari.
// Returns array instead of HTMLCollection.
;(function(constructor) {
if (constructor &&
constructor.prototype &&
constructor.prototype.lastElementChild == null) {
Object.defineProperty(constructor.prototype, 'lastElementChild', {
get: function() {
var node, nodes = this.childNodes, i = nodes.length - 1;
while (node = nodes[i--]) {
if (node.nodeType === 1) {
return node;
}
}
return null;
}
});
}
})(window.Node || window.Element);
| 规范 | 状态 | 备注 |
|---|---|---|
| {{SpecName('DOM WHATWG', '#dom-Element-lastelementchild', 'Element.lastElementChild')}} | {{Spec2('DOM WHATWG')}} | Splitted the ElementTraversal interface in {{domxref("ChildNode")}} and Element. This method is now defined on the latter.The {{domxref("Document")}} and {{domxref("DocumentFragment")}} implemented the new interfaces. |
| {{SpecName('Element Traversal', '#attribute-lastElementChild', 'ElementTraversal.lastElementChild')}} | {{Spec2('Element Traversal')}} | Added its initial definition to the ElementTraversal pure interface and use it on {{domxref("Element")}}. |
{{Compat("api.Element.lastElementChild")}}