每当我尝试在影子 dom 脚本标记内使用 document.getElementById
时,我总是得到 null
我看了问题here和 here ,但没有一个答案有帮助。
现在我正在使用这个脚本,但我很确定有更好的方法来做到这一点。
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>
关于javascript - 如何从 Shadow dom 内部获取ElementById,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60763641/