Search code examples
javascriptshadow-domcustom-element

ShadowRoot property is null despite open


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)
enter image description here

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.


Solution

  • 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);
    } )