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:

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:

https://kevinsimper.github.io/queryselector-web-component/index.html

and the source code here:

Image for post
Image for post

Written by

I really like building stuff with React.js and Docker and also Meetups ❤

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store