【问题标题】:How do I getElementById from inside a shadow dom如何从影子 dom 中获取ElementById
【发布时间】:2020-03-19 19:11:14
【问题描述】:

每当我尝试使用 document.getElementById 在 shadow dom 脚本标签中时,我总是得到 null 我查看了herehere 的问题,但没有一个答案有帮助。

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

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

【问题讨论】:

  • 实际上不,这是影子 DOM 的全部目的。它将其中的元素与真实的 DOM 隔离开来,这样父 DOM 的选择器就不会返回影子 DOM 中的元素。这适用于 CSS 和 JavaScript。

标签: javascript shadow-dom


【解决方案1】:

这就是在影子 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'));
&lt;with-shadowroot&gt;&lt;/with-shadowroot&gt;

【讨论】:

    猜你喜欢
    • 2012-02-12
    • 2013-04-06
    • 2019-10-12
    • 1970-01-01
    • 1970-01-01
    • 2020-02-22
    • 1970-01-01
    • 2019-08-01
    • 2015-07-10
    相关资源
    最近更新 更多