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.
The element that the tree is attached to (<my-header>) is called the shadow host and the host has a property called shadowRoot that refers to the shadow root. The shadow root is a document fragment that is attached to the host element and it has a host property that identifies its host element.
shadowRoot is always null . We can only access the shadow DOM by the reference returned by attachShadow (and probably hidden inside a class). Browser-native shadow trees, such as <input type="range"> , are closed. There's no way to access them.
You can't remove a shadow root once you add it. However, you can replace it with a newer one. As mentioned here, http://www.html5rocks.com/en/tutorials/webcomponents/shadowdom-301/, the newest shadow root "wins" and becomes the rendered root.
Basic usage. If you attach a shadow root to a custom element with mode: closed set, you won't be able to access the shadow DOM from the outside — myCustomElem. shadowRoot returns null . This is the case with built in elements that contain shadow DOMs, such as <video> .
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);
} )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With