[英]Is there a way to use querySelector to get an open shadow dom
假設我創建並插入了這樣的元素
<template id="react-web-component">
<span>template stuff</span
<script src="/static/js/bundle.js" type="text/javascript"></script>
</template>
<script>
(function (window, document) {
const doc = (document._currentScript || document.currentScript).ownerDocument;
const proto = Object.create(HTMLElement.prototype, {
attachedCallback: {
value: function () {
const template = doc.querySelector('template#react-web-component').content;
const shadowRoot = this.attachShadow({ mode: 'open' });
shadowRoot.appendChild(template.cloneNode(true));
},
},
});
document.registerElement('react-web-component', { prototype: proto });
})(window, document);
</script>
<react-web-component></react-web-component>
現在我想使用querySelector
來訪問我的元素的開放影子 dom。 像這樣:
document.querySelector('react-web-component::shadow')
但這不起作用。 還有別的辦法嗎?
編輯以回應@Supersharp 的回答
對不起,我沒有說清楚。 我正在使用 webpack 的
style-loader
,它只接受與document.querySelector
一起使用的 CSS 選擇器,所以我要的是一個 CSS 選擇器,我可以通過這種方式使用。
通過Shadow主機的shadowRoot
屬性獲取它:
document.querySelector('react-web-component').shadowRoot
更新資料
曾經有這種CSS選擇器,但現在已棄用。
也許您可以嘗試使用普通DOM而不是陰影DOM。
這應該可以解決問題:
const querySelectorAll = (node,selector) => {
const nodes = [...node.querySelectorAll(selector)],
nodeIterator = document.createNodeIterator(node, Node.ELEMENT_NODE);
let currentNode;
while (currentNode = nodeIterator.nextNode()) {
if(currentNode.shadowRoot) {
nodes.push(...querySelectorAll(currentNode.shadowRoot,selector));
}
}
return nodes;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.