Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use JS to serialize the current DOM?

Tags:

javascript

dom

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).

like image 918
George Mauer Avatar asked Jul 18 '12 23:07

George Mauer


2 Answers

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;
}
like image 64
radhe001 Avatar answered Sep 28 '22 14:09

radhe001


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);
};
like image 20
sdgfsdh Avatar answered Sep 28 '22 16:09

sdgfsdh