GetElementById from within Shadow DOM

一个人想着一个人 提交于 2020-02-21 12:26:53

问题


I have a custom-element with shadow DOM, which listens to attribute target change.
target is supposed to be the ID of the element which my component is supposed to be attached to.
I've tried using querySelector and getElementById to get the element of the outer DOM, but it always returns null. Eg.:

console.log(document.getElementById(target));
console.log(document.querySelector('#' + target));

Both of the above return null.
Is there a way to get reference to the element in the parent document from within shadow DOM ?


回答1:


You just have to call Shadow​Root.

this.shadowRoot.getElementById('target') should work.

Here's an example, the get syntax will bind an object property to a function.

get target() {
    return this.shadowRoot.getElementById('target');
}


来源:https://stackoverflow.com/questions/55101967/getelementbyid-from-within-shadow-dom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!