ShadowRoot property is null despite open

大憨熊 提交于 2020-05-15 11:18:19

问题


I'm trying to access the ShadowRoot on my element and the property element.shadowRoot is returning null.
The ShadowDOM is defined as mode: 'open', which is correct, I can even console.log(element) to see all of the properties and shadowRoot IS an object of ShadowRoot type.

In my app I am trying to access the property like so:

let el = document.getElementById('elementId');
...
console.log(el);
console.log("this.shadowRoot = ???");
console.log(el.shadowRoot);

Is this okay?

Attached are the console.log() output from the console, as you can see the shadowRoot definitely is there.
(From the Firefox console)

I have tried in both latest Firefox and Chrome, both have same result.
What am I doing wrong?

Thanks

Edit

I have created a little JSFiddle.
If you press F12 and view the console you can see that the element is logged and shows the shadowRoot property, but logging the shadowRoot displays null.

I wonder if this is a bug? Perhaps it is not fully implemented yet?

I have seen Element.shadowRoot in firefox but I am using the latest (65) of Firefox and (72) Chrome.


回答1:


Be careful of the script execution order.

In your example you are trying to get the shadowRoot propery before the Custom Element is defined.

It works when you get the value at the right time.

You could use the whenDefined() method to be sure the element is defined:

customElements.whenDefined( 'web-component ').then( () => {
    let el = document.getElementById('elementId');
    console.log(el.shadowRoot);
} )


来源:https://stackoverflow.com/questions/54610139/shadowroot-property-is-null-despite-open

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