Is there a way to use querySelector to get an open shadow dom

Viewed 3999

Suppose I created and inserted an element like this

<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>

Now I wanna use a querySelector to access the open shadow dom of my element. Like this:

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

But this does not work. Is there any other way?

edit in response to @Supersharp 's answer

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.

3 Answers

This should solve the problem:

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;
}
Related