I would like to use javascript to serialize the current state of the DOM tree to a string. The resulting format doesn't matter so much though I would prefer html.
Is there an easy way to do this?
For the record, I would like to automate downloading a page with PhantomJs, manipulating it with js scripts, and save the current state of the page (but not as an image or pdf).
You can serialize any element or part of dom using XMLSerializer .Here is the code
Element.prototype.innerText = function(){
var serializer = new XMLSerializer();
var serialized = serializer.serializeToString(this);
return serialized;
}
You can run this in your browser console:
new XMLSerializer().serializeToString(document);
Replace document
with any node. For example, combined with a CSS select:
new XMLSerializer().serializeToString(document.querySelector('h1'));
"http://www.w3.org/1999/xhtml\" itemprop=\"name\" class=\"grid--cell fs-headline1 fl1 ow-break-word mb8\">Can I use JS to serialize the current DOM?"
We can wrap this in a function:
const serializeElement = el => {
const serializer = new XMLSerializer();
return serializer.serializeToString(el);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With