document-outerhtml/src/ index.js
30 lines
729 B

  1. import doctypeToString from 'doctype-to-string'
  2. export default function documentOuterHTML(document) {
  3. if (!document
  4. || document.nodeType === undefined
  5. || document.nodeType !== document.DOCUMENT_NODE
  6. ) {
  7. throw new TypeError('Expected a Document')
  8. }
  9. const html = [...document.childNodes]
  10. .map(node => nodeToString(node))
  11. .join('\n')
  12. return html
  13. }
  14. function nodeToString(node) {
  15. switch (node.nodeType) {
  16. case node.ELEMENT_NODE:
  17. return node.outerHTML
  18. case node.TEXT_NODE:
  19. return node.textContent
  20. case node.COMMENT_NODE:
  21. return `<!--${node.textContent}-->`
  22. case node.DOCUMENT_TYPE_NODE:
  23. return doctypeToString(node)
  24. default:
  25. throw new TypeError(`Unexpected node type: ${node.nodeType}`)
  26. }
  27. }