typescript 如何从影子根中选择元素标记

omhiaaxx  于 2023-06-07  发布在  TypeScript
关注(0)|答案(2)|浏览(216)

我试图从影子根选择一个标签,但不工作。那么,如何从嵌套的影子根元素中选择特定的标签呢?

#shadow-root(open)
<start>
   #shadow-root(open)
     <plural>
       #shadow-root(open)
           <main>
              #shadow-root(open)
                 <content>
                    <p>..text..</p>
                 </content>
           </main>
     </plural> 
</starts>

typescript :

let inside = this.shadowRoot.querySelector('content').innerHTML;
  console.log(inside);
oxcyiej7

oxcyiej71#

对于未知级别的shadowRoot,您需要“遍历DOM”并潜入shadowRoots:

<my-component>
  #shadow-root(open)
  <my-component>
    #shadow-root(open)
    <my-component>
      #shadow-root(open)
      <content>
        <p>..text..</p>
      </content>
    </my-component>
  </my-component>
</my-component>

<script>
customElements.define("my-component", class extends HTMLElement {
  constructor() {
    super().attachShadow({mode:"open"}).innerHTML = `<slot></slot>`;
  }
})

const shadowDive = (
  el,
  selector,
  match = (el, root) => {
    console.warn('match', el, root);
  },
  root = el.shadowRoot || el
) => {
  root.querySelector(selector) && match(root.querySelector(selector), root);
  [...root.querySelectorAll("*")].map(el => shadowDive(el, selector, match));
}
shadowDive(document.body, "content"); // note optional parameters
</script>
o75abkj4

o75abkj42#

要从嵌套的影子根中选择元素,可以使用querySelector().shadowRoot方法访问每个影子根级别:

// Assuming you have the parent element that contains the shadow root
const parentElement = document.querySelector('#start');

// Access the first shadow root
const firstShadowRoot = parentElement.shadowRoot;

// Access the second shadow root
const secondShadowRoot = firstShadowRoot.querySelector('plural').shadowRoot;

// Access the third shadow root
const thirdShadowRoot = secondShadowRoot.querySelector('main').shadowRoot;

// Get the paragraph inside the third shadow root
const p = thirdShadowRoot.querySelector('p');

console.log(p.textContent);

**请注意:**您不能跳过一个影子DOM级别,因此请确保您从DOM的顶部开始跟踪每个级别。

另一个可能有帮助的提示:
当处理一个复杂的DOM,其中包含许多嵌套的Shadow DOM时,找到元素路径的最佳方法是使用devtools:right click on the element > Copy > Copy js path(Chrome示例)

相关问题