我试图从影子根中选择一个标签,但不起作用。那么,如何从嵌套的影子根元素中选择特定标签?
#shadow-root(open)
<start>
#shadow-root(open)
<plural>
#shadow-root(open)
<main>
#shadow-root(open)
<content>
<p>..text..</p>
</content>
</main>
</plural>
</starts>
打字稿:
let inside = this.shadowRoot.querySelector('content').innerHTML;
console.log(inside);
要从嵌套影子根中选择元素,您可以使用
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 顶部开始跟踪每个级别。
另一个可能有帮助的提示:
当处理涉及许多嵌套 Shadow DOM 的复杂 DOM 时 找到元素路径的最佳方法是使用开发工具:
(Chrome 示例)right click on the element > Copy > Copy js path
对于未知级别的
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>