如何从阴影中获取 ElementById dom

How do I getElementById from inside a shadow dom

每当我尝试在阴影 dom 脚本标签 中使用 document.getElementById 时,我总是得到 null 我查看了问题 here and ,但 none 的答案有所帮助。

我现在正在使用这个脚本,但我很确定有更好的方法来做到这一点。

window.document.body.getElementsByClassName('calculator')[0].getElementsByClassName('content')[0].shadowRoot.getElementById('test')

这就是在阴影中使用选择器的方式 DOM。您必须先找到 shadowRoot,然后从中调用 getElementById

customElements.define("with-shadowroot", class extends HTMLElement {  
    constructor() {
        super()
          .attachShadow({ mode: 'open' })
          .innerHTML = `<div><div id="some-div">I'm inside shadowDOM!</div></div>`;
    }
});

console.log(document.getElementById('some-div'));

const divs = document.getElementsByTagName('with-shadowroot');
console.log(divs[0].shadowRoot.getElementById('some-div'));
<with-shadowroot></with-shadowroot>