document.querySelector with Web Components
If you are using web components with LitElement for example, and then you try to use document.querySelector and it doesn’t find anything in the document, but you can clearly see it in the developer tools. Super annoying and then you search for “document.querySelector web components” and no good results come up! okay, everything is super annoying right now!
The reason is that web components can use the new ShadowDom, which encapsulate the DOM elements that can be attached to the DOM. You actually don’t have to use ShadowDom, but it more the rule than the outlier.
Show how do you query shadowdom?
It is more complicated and there is no way that you can do it as easy as before, you will have do dig manually down throw the components yourself.
We want get the button element.
We can’t do this:
document.querySelector('button') // won't work
We will have to do this:
So ShadowRoot is root for that component and that querySelector will work inside that subtree.
I created a example here that you can see:
and the source code here: