如何获取包含给定元素的 shadowRoot 的引用

how to obtain ref to shadowRoot which contains given element

我正在使用网络组件。

我有一个这样的节点树,正如 chrome 开发工具检查员所描述的那样:

<div>
-- <my-fancy-custom-elem> (this is the web component)
---- #shadow-root
------ <div class="button-container">
-------- <button class="a-button-in-a-web-comp">

我能够通过在 Web 组件 class 之外启动的事件侦听器获取对 <button> 的引用。

与此类似:

document.addEventListener("click", (event) => {
   const clickedElem = event.composedPath()[0]
   if(clickedElem.matches('.a-button-in-a-web-comp')){
     console.log(clickedElem.parentNode.parentNode)
   }
});

我可以通过调用 clickedElem.parentNode.parentNode 获得对 #shadow-root 的引用。但是,我正在寻找一种方法来可靠地获取 <button> 的阴影根祖先,无论它在树中的位置有多深。即使我不知道它住的树有多深。

换句话说,当我引用 X 时,我正在寻找一种可靠的方法 return 第一个包含 X 元素的影子根。

您可以调用 clickedElem.getRootNode() 获取 shadowRoot ,如下面的代码片段所示:

class CustomButton extends HTMLElement{
  constructor(){
    super();
    this.attachShadow({"mode": "open"});
    this.shadowRoot.innerHTML = `
      <div>
        <button class="a-button-in-a-web-comp">Button</button>
       </div>
    `;
  }
}
customElements.define('custom-button', CustomButton);

document.addEventListener("click", (event) => {
   const clickedElem = event.composedPath()[0];
   if(clickedElem.matches('.a-button-in-a-web-comp')){
     console.log(clickedElem.getRootNode())
   }
})
<custom-button></custom-button>