DEV Community

Michael Puckett
Michael Puckett

Posted on

How can I get rendered innerHTML that includes Shadow DOM?

I'm using web components with shadow DOM on a project and I would like to copy the innerHTML of the page as rendered.

I think I need to write a function loops over each DOM node and gets either the shadow DOM children if available or else the light DOM children.

node.shadowRoot ? node.shadowRoot.children : node.children

I've been having trouble getting it right, and I'm surprised I can't find anything on Google.

Top comments (4)

Collapse
 
pankajpatel profile image
Pankaj Patel •

I am still wondering why do you need to copy innerHTML to stadowRoot.

If it is already rendered then why do you need to copy the innerHTML; and if you are passing HTML as template, then you should make use of template tag. See how to use shadowDom here: time2hack.com/introduction-to-webc...

and HTML template tagL time2hack.com/introduction-to-webc...

Collapse
 
mpuckett profile image
Michael Puckett •

Iโ€™m building a tool that parses the page HTML and does static checking for accessibility, SEO, etc. Right now itโ€™s only getting the light DOM, no shadow DOM. So if there is a top level web component which has many nested web components inside its shadow root, none of the shadow DOM elements will be there. So I need an alternative that gets the shadow DOM children instead and returns a string of rendered HTML.

Make sense? ๐Ÿ˜…

Collapse
 
pankajpatel profile image
Pankaj Patel •

Makes sense. Though now it depends on how you are getting the HTML page which has all the webcomponents.

ShadowDOM exists in DOM, so if it is a scraped page, shadowRoot will not have any elements inside it.

Another fact to consider is that web components with shadowDOM might be created with closed mode; in that case, you can not access the inner DOM of shadowDOM.

Collapse
 
mpuckett profile image
Michael Puckett •

Update: I opened an issue for this with W3C because I think it should be available natively. Check it out and weigh in here:

github.com/w3c/DOM-Parsing/issues/58