最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can I use JS to serialize the current DOM? - Stack Overflow

programmeradmin3浏览0评论

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

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

Share Improve this question asked Jul 18, 2012 at 23:04 George MauerGeorge Mauer 122k140 gold badges396 silver badges630 bronze badges 3
  • 2 Yeah, just take the body element and fetch the html with .innerHTML, for example: jsfiddle/zvQkH – TheZ Commented Jul 18, 2012 at 23:06
  • +1 but unfortunately this won't work from PhantomJs for some reason – George Mauer Commented Jul 26, 2012 at 13:56
  • @TheZ That would not preserved the saved states of elements. For example, you would loose which select box options are selected and which radio buttons are checked. – Developer Webs Commented Mar 21, 2018 at 16:28
Add a ment  | 

2 Answers 2

Reset to default 7

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, bined with a CSS select:

new XMLSerializer().serializeToString(document.querySelector('h1'));

"http://www.w3/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);
};
发布评论

评论列表(0)

  1. 暂无评论