gpt4 book ai didi

javascript - 有没有办法使用 querySelector 来获取打开的影子 dom

转载 作者:行者123 更新时间:2023-11-30 09:32:16 25 4
gpt4 key购买 nike

假设我创建并插入了这样一个元素

<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 访问我的元素的 open shadow dom。像这样:

document.querySelector('react-web-component::shadow')

但这行不通。还有其他办法吗?

编辑以回应@Supersharp 的回答

Sorry, I wasn't making myself clear. I am using webpack's style-loader that only accepts a CSS selector that it uses with document.querySelector, so what I am asking is for a CSS selector I can use this way.

最佳答案

通过Shadow宿主的shadowRoot属性获取:

document.querySelector('react-web-component').shadowRoot

更新

以前有这种CSS选择器,现在弃用了。

也许您可以尝试使用普通 DOM 而不是 Shadow DOM。

关于javascript - 有没有办法使用 querySelector 来获取打开的影子 dom,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45571378/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com