Convert a DOM DocumentType into a string, e.g. "<!DOCTYPE html>"

doctype-to-string/src/ index.js
24 lines
911 B

  1. export default function doctypeToString(doctype) {
  2. if (doctype === null) {
  3. return ''
  4. }
  5. // Checking with instanceof DocumentType might be neater, but how to get a
  6. // reference to DocumentType without assuming it to be available globally?
  7. // To play nice with custom DOM implementations, we resort to duck-typing.
  8. if (!doctype
  9. || doctype.nodeType !== doctype.DOCUMENT_TYPE_NODE
  10. || typeof doctype.name !== 'string'
  11. || typeof doctype.publicId !== 'string'
  12. || typeof doctype.systemId !== 'string'
  13. ) {
  14. throw new TypeError('Expected a DocumentType')
  15. }
  16. const doctypeString = `<!DOCTYPE ${doctype.name}`
  17. + (doctype.publicId ? ` PUBLIC "${doctype.publicId}"` : '')
  18. + (doctype.systemId
  19. ? (doctype.publicId ? `` : ` SYSTEM`) + ` "${doctype.systemId}"`
  20. : ``)
  21. + `>`
  22. return doctypeString
  23. }