簡體   English   中英

我如何從 shadow dom 內部獲取 ElementById

[英]How do I getElementById from inside a shadow dom

每當我嘗試在 shadow dom 腳本標簽中使用document.getElementById ,我總是得到null我查看了這里這里的問題,但沒有一個答案有幫助。

現在我正在使用這個腳本,但我很確定有更好的方法來做到這一點。

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

這就是在 shadow 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM