Skip to content

Instantly share code, notes, and snippets.

@developit
Created March 4, 2019 18:50
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 developit/9330462aae9f6c3f4ff6e2f4606da594 to your computer and use it in GitHub Desktop.
Save developit/9330462aae9f6c3f4ff6e2f4606da594 to your computer and use it in GitHub Desktop.
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