2017-08-08 33 views
0

假设我创建并插入一个元素这样有没有办法使用querySelector得到一个开放的影子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选择器。

回答

1

由影子主机的shadowRoot财产得到它:

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

更新以前是这样的CSS选择器的

在那里,但现在它已经过时了。

也许你可以尝试使用正常的DOM而不是Shadow DOM。

+0

对不起,我没有说清楚。我正在使用webpack的'style-loader',它只接受一个与“document.querySelector”一起使用的CSS选择器,所以我所要求的是可以使用这种方式的CSS选择器。 – Lukas

+1

没有选择器。也许你应该考虑不使用影子dom。 – Supersharp

+0

做出答案,我会接受 – Lukas

相关问题