有没有办法使用 querySelector 来获取一个开放的 shadow dom

Luk*_*kas 3 javascript shadow-dom html5-template

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

<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>
Run Code Online (Sandbox Code Playgroud)

现在我想使用 aquerySelector来访问我的元素的开放阴影 dom。像这样:

document.querySelector('react-web-component::shadow')
Run Code Online (Sandbox Code Playgroud)

但这不起作用。有没有其他办法?

编辑以回应@Supersharp 的回答

对不起,我没有说清楚。我使用的 webpackstyle-loader只接受一个 CSS 选择器,它与 一起使用document.querySelector,所以我要的是一个我可以用这种方式使用的 CSS 选择器。

Sup*_*arp 5

通过shadowRootShadow主机的属性获取:

document.querySelector('react-web-component').shadowRoot
Run Code Online (Sandbox Code Playgroud)

更新

曾经有这种 CSS 选择器,但现在已弃用。

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


euv*_*uvl 0

如果我理解正确的话,它有一个编辑草稿(因此它还不存在)。

https://drafts.c​​sswg.org/css-scoping/#selectors

所以答案是“不”,你不能这样做。