[英]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.