Created
March 4, 2019 18:50
-
-
Save developit/9330462aae9f6c3f4ff6e2f4606da594 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function serialize(node) { | |
if (node.nodeType === 3) { | |
return node.data; | |
} | |
else if (node.nodeType === 8) { | |
return '<!--' + node.data + '-->'; | |
} | |
else if (node.nodeType === 1 || node.nodeType === 9) { | |
let str = '<' + node.nodeName; | |
const attrs = []; | |
for (let i=0; i<node.attributes.length; i++) { | |
attrs.push(node.attributes[i].name); | |
} | |
attrs.sort(); | |
for (let i=0; i<attrs.length; i++) { | |
const name = attrs[i]; | |
const value = node.getAttribute(name); | |
str += ' ' + name; | |
if (value !== '') { | |
str += '="' + value + '"'; | |
} | |
} | |
str += '>'; | |
for (let i=0; i<node.childNodes.length; i++) { | |
str += serialize(node.childNodes[i]); | |
} | |
str += '</' + node.nodeName + '>'; | |
return str; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment