Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize an HTML DOM including Shadow DOM?

I want to serialize an entire HTML DOM including Shadow DOM trees into a string i.e. including both the shadow host and shadow root in a way that they can be reconstructed.

I can programatically access the Shadow DOM via .shadowRoot.innerHTML but calling .outerHTML on the entire DOM or using an XMLSerializer does not include the shadowRoot.

Is there a way to serialize the entire HTML document including Shadow DOM trees?

like image 825
Resonance Avatar asked May 04 '16 00:05

Resonance


People also ask

What is HTML shadow DOM?

Shadow DOM allows hidden DOM trees to be attached to elements in the regular DOM tree — this shadow DOM tree starts with a shadow root, underneath which you can attach any element, in the same way as the normal DOM.

Which selector can work for shadow DOM elements?

There's no selector that can directly affect shadow DOM styles from the document. But just as we expose methods to interact with our component, we can expose CSS variables (custom CSS properties) to style it. Custom CSS properties exist on all levels, both in light and shadow.

Why do we need shadow DOM?

Shadow DOM is very important for web components because it allows specific sections of the HTML document to be completely isolated from the rest of the document. This means CSS styles that are applied to the DOM are not applied to the Shadow DOM, and vice versa.


1 Answers

I want to serialize an entire HTML DOM including Shadow DOM trees into a string i.e. including both the shadow host and shadow root in a way that they can be reconstructed.

Note, shadowRoot nodes are not clonable; though you should be able to iterate childNodes of shadowRoot to retrieve .nodeValue or .innerHTML of each node within shadowRoot.

var elems = document.getElementById("host").shadowRoot.childNodes;
var shadowHTML = "";
for (var i = 0; i < elems.length; i++) {
  shadowHTML += elems[i].nodeValue || elems[i].outerHTML;
}

Alternatively you can call .innerHTML chained to .treeRoot property of shadowRoot to retrieve full html of shadowRoot.

var shadowHTML = document.getElementById("host").shadowRoot.treeRoot.innerHTML;

I can programatically access the Shadow DOM via .shadowRoot.innerHTML but calling .outerHTML on the entire DOM or using an XMLSerializer does not include the shadowRoot.

You can use .outerHTML called on .host to retrieve html of element within document which hosts shadowRoot.

var host = document.getElementById("host").shadowRoot.host.outerHTML;

The shadowRoot can then be reconstructed by creating a <template> element, setting .innerHTML to variable shadowHTML which is string .treeRoot.innerHTML; appending newly created template element to a shadowRoot.

like image 172
guest271314 Avatar answered Oct 23 '22 12:10

guest271314