ParentNode.lastElementChild read-only property returns the object's last child 元素 or null if there are no child elements.

注意: This property was initially defined in the ElementTraversal pure interface. As this interface contained two distinct set of properties, one aimed at 节点 that have children, one at those that are children, they have been moved into two separate pure interfaces, ParentNode and ChildNode 。在此情况下, lastElementChild moved to ParentNode . This is a fairly technical change that shouldn't affect compatibility.

句法

const element = node.lastElementChild
					

范例

<ul id="foo">
  <li>First  (1)</li>
  <li>Second (2)</li>
  <li>Third  (3)</li>
</ul>
<script>
const foo = document.getElementById('foo');
console.log(foo.lastElementChild.textContent); // logs: Third (3)
</script>
					

Polyfill

The code below adds support of lastElementChild() to Document and DocumentFragment in Internet Explorer and Safari.

// Overwrites native 'lastElementChild' prototype.
// 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);
					

规范

规范 状态 注释
DOM
The definition of 'ParentNode.lastElementChild' in that specification.
实时标准 Splitted the ElementTraversal interface in ChildNode and ParentNode . This method is now defined on the latter.
Document and DocumentFragment implemented the new interfaces.

浏览器兼容性

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. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
lastElementChild Chrome 1 Edge 12 Firefox 3.5 IE 9 Opera 10 Safari 4 WebView Android Yes Chrome Android Yes Firefox Android 4 Opera Android Yes Safari iOS Yes Samsung Internet Android Yes
Support on Document and DocumentFragment Chrome 29 Edge ≤79 Firefox 25 IE No Opera 16 Safari No WebView Android Yes Chrome Android Yes Firefox Android ? Opera Android ? Safari iOS No Samsung Internet Android Yes

图例

完整支持

完整支持

不支持

不支持

兼容性未知 ?

兼容性未知

实验。期望将来行为有所改变。

实验。期望将来行为有所改变。

另请参阅

元数据

  • 最后修改: