- import doctypeToString from 'doctype-to-string'
-
- export default function documentOuterHTML(document) {
- if (!document
- || document.nodeType === undefined
- || document.nodeType !== document.DOCUMENT_NODE
- ) {
- throw new TypeError('Expected a Document')
- }
- const html = [...document.childNodes]
- .map(node => nodeToString(node))
- .join('\n')
- return html
- }
-
- function nodeToString(node) {
- switch (node.nodeType) {
- case node.ELEMENT_NODE:
- return node.outerHTML
- case node.TEXT_NODE:
- return node.textContent
- case node.COMMENT_NODE:
- return `<!--${node.textContent}-->`
- case node.DOCUMENT_TYPE_NODE:
- return doctypeToString(node)
- default:
- throw new TypeError(`Unexpected node type: ${node.nodeType}`)
- }
- }
|