ElementInternals: shadowRoot 属性

shadowRootElementInternals 接口的一个只读属性,它返回该元素的 ShadowRoot

如果元素有 Shadow Root,则返回一个 ShadowRoot 对象;否则返回 null

示例

下面的示例在调用 HTMLElement.attachInternals() 后立即将 shadowRoot 的值打印到控制台。此时,该值为 null。在调用 Element.attachShadow() 后,元素具有 Shadow Root,并且 shadowRoot 返回代表它的对象。

js
class MyCustomElement extends HTMLElement {
  constructor() {
    super();
    this.internals_ = this.attachInternals();

    console.log(this.internals_.shadowRoot); // null

    this.attachShadow({ mode: "open" });

    console.log(this.internals_.shadowRoot); // a ShadowRoot object
  }
}

规范

规范
HTML
# dom-elementinternals-shadowroot

浏览器兼容性