Skip to content

Instantly share code, notes, and snippets.

@thysultan
Forked from Thaina/dom-to-json.js
Created June 11, 2016 08:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thysultan/9dd394588019b6c63fda26718d4bcd10 to your computer and use it in GitHub Desktop.
Save thysultan/9dd394588019b6c63fda26718d4bcd10 to your computer and use it in GitHub Desktop.
Stringify DOM nodes using JSON (and revive again)
/** @param {Node|HTMLElement} node */
function toJSON(node) {
if(!node)
node = this;
var obj = { nodeType: node.nodeType };
if(node.tagName)
obj.tagName = node.tagName.toLowerCase();
else if(node.nodeName)
obj.nodeName = node.nodeName;
if(node.nodeValue)
obj.nodeValue = node.nodeValue;
if(node.attributes && node.attributes.length > 0)
{
obj.attributes = new Array(node.attributes.length).reduce(function(obj,n,i) {
var attr = node.attributes.item(i);
obj[attr.nodeName] = attr.nodeValue;
return obj;
},{});
}
if(node.childNodes && node.childNodes.length > 0)
{
obj.childNodes = new Array(node.childNodes.length).map(function(n,i) {
return toJSON(node.childNodes[i]);
});
}
return obj;
}
/** @returns {Node} node */
function toDOM(obj) {
if(typeof obj == 'string')
obj = JSON.parse(obj);
switch(obj.nodeType)
{
case Node.TEXT_NODE:
return document.createTextNode(obj.nodeValue);
case Node.COMMENT_NODE:
return document.createComment(obj.nodeValue);
case Node.DOCUMENT_NODE:
return document.implementation.createDocument();
case Node.DOCUMENT_TYPE_NODE:
return document.implementation.createDocumentType(obj.nodeName);
case Node.DOCUMENT_FRAGMENT_NODE:
var frag = document.createDocumentFragment();
obj.childNodes.forEach(function (child) {
frag.appendChild(toDOM(child));
});
return frag;
case Node.ELEMENT_NODE:
var element = document.createElement(obj.tagName);
for(var key in obj.attributes)
element.setAttribute(key,obj.attributes[key]);
obj.childNodes.forEach(function(child) {
element.appendChild(toDOM(child));
});
return element;
default:
return undefined;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment