how to serialize DOM?

260 views
Skip to first unread message

yaci

unread,
Feb 13, 2012, 5:02:40 PM2/13/12
to Web Consistency Testing
At the end of Mr. Menard's presentation it is said that DOM data is
serialized to JSON using javascript. I would like to ask how I can
actually serialize this data? I've tried
JSON.stringify(window.document) but it resulted with an error. I've
done a quick search but it seems to be a non-trivial task. Is there
any easy way to do it?

Kevin Menard

unread,
Feb 13, 2012, 5:28:08 PM2/13/12
to web-consist...@googlegroups.com
Hi,

I don't actually serialize the whole DOM. I only serialize the
attributes I need. E.g., width, height, left, top, opacity, etc.
These are simple numeric values and won't induce the cyclic graph
error you likely encountered.

This does imply that you'll need to traverse the DOM yourself. I use
a bit of jQuery to help with that and then just perform a Depth First
Search using something of a visitor pattern that extracts out the
values of each node as I visit it. Something like the following would
do the search:

function search(node) {
var ret = {}

var $node = $(node);

// Extract whatever

$node.children().each(function() {
ret['children'].push(search(this));
});

return ret;
}

Pulling what you need for your case and optimizing that is up to you.
If speed is a major concern, you may want to forego jQuery completely.

--
Kevin

Reply all
Reply to author
Forward
0 new messages