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.
<div><my-component><button>Hello</button></my-component></div>
We want get the button element.
We can’t do this:
document.querySelector('button') // won't work
We will have to do this:
document.querySelector('my-component').shadowRoot.querySelector('button')
So ShadowRoot is root for that component and that querySelector will work inside that subtree.
I created a example here that you can see:
https://kevinsimper.github.io/queryselector-web-component/index.html
and the source code here: