Reputation: 116
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?
Upvotes: 8
Views: 2444
Reputation: 1
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
.
Upvotes: 2