Created
June 4, 2018 04:25
-
-
Save kmck/70d53bbccfb5f73329b436c5d13598fa 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 serializeNodeToString(node) { | |
if (typeof XMLSerializer !== 'undefined') { | |
return new XMLSerializer().serializeToString(node); | |
} | |
if (node.outerHTML != null) { | |
return node.outerHTML; | |
} else if (node instanceof Document) { | |
return node.documentElement && node.documentElement.outerHTML | |
? node.documentElement.outerHTML | |
: ''; | |
} else if (node instanceof DocumentType) { | |
const docTypeAttrs = [ | |
node.name, | |
node.publicId ? 'PUBLIC' : '', | |
node.systemId && !node.publicId ? 'SYSTEM' : '', | |
node.publicId ? `"${node.publicId}"` : '', | |
node.systemId ? `"${node.systemId}"` : '', | |
].filter(v => v).join(' '); | |
return `<!DOCTYPE ${docTypeAttrs}>`; | |
} | |
const el = document.createElement('body'); | |
el.appendChild(node); | |
return el.innerHTML; | |
} | |
function serializeNodeToHtmlString(node) { | |
const serialized = serializeNodeToString(node); | |
// XMLSerializer puts xmlns on documentElement | |
const { namespaceURI } = node.documentElement || node; | |
if (namespaceURI) { | |
const { namespaceURI: ownerNamespaceURI } = node.ownerDocument | |
? node.ownerDocument.documentElement | |
: node.documentElement; | |
if (namespaceURI === ownerNamespaceURI) { | |
return serialized.replace(` xmlns="${namespaceURI}"`, '') | |
} | |
} | |
return serialized; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment