Node: parentElement 属性

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

Node 接口的只读 parentElement 属性返回 DOM 节点的父 Element,如果该节点没有父节点,或者其父节点不是 DOM Element,则返回 null。另一方面,Node.parentNode 则返回任何类型的父节点,而不考虑其类型。

当前节点的父 Element,如果没有则为 null

示例

使用 parentElement

此示例将 node 的父节点的文本颜色设置为红色。

js
if (node.parentElement) {
  node.parentElement.style.color = "red";
}

parentElement 为 null

如果节点没有父节点(例如,因为它未附加到树中)或者其父节点不是 Element,则 parentElement 可能为 null。另一方面,Node.parentNode 始终返回父节点,该节点可以是 Document 或其他节点类型。

html
<!doctype html>
<html lang="en-US">
  <body>
    <script>
      const html = document.querySelector("html");
      console.log(html.parentElement); // null
      console.log(html.parentNode); // document
    </script>
  </body>
</html>

规范

规范
DOM
# ref-for-dom-node-parentelement①

浏览器兼容性

另见