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

Throw a TypeError when appropriate.

tags/v0.1.2
Gerben 3 years ago
parent
commit
c96c61a111
2 changed files with 15 additions and 0 deletions
  1. +11
    -0
      src/index.js
  2. +4
    -0
      test/index.js

+ 11
- 0
src/index.js View File

@@ -2,6 +2,17 @@ export default function doctypeToString(doctype) {
if (doctype === null) {
return ''
}
// Checking with instanceof DocumentType might be neater, but how to get a
// reference to DocumentType without assuming it to be available globally?
// To play nice with custom DOM implementations, we resort to duck-typing.
if (!doctype
|| doctype.nodeType !== doctype.DOCUMENT_TYPE_NODE
|| typeof doctype.name !== 'string'
|| typeof doctype.publicId !== 'string'
|| typeof doctype.systemId !== 'string'
) {
throw new TypeError('Expected a DocumentType')
}
const doctypeString = `<!DOCTYPE ${doctype.name}`
+ (doctype.publicId ? ` PUBLIC "${doctype.publicId}"` : '')
+ (doctype.systemId


+ 4
- 0
test/index.js View File

@@ -17,6 +17,10 @@ test('should return empty string if doctype is null', t => {
t.is(doctypeToString(null), '')
})

test('should throw if argument is not a DocumentType', t => {
t.throws(() => doctypeToString('a string, for example.'), TypeError)
})

test('should work for a HTML5-ish doctype', t => {
const doctype = '<!DOCTYPE html>'
const doc = makeStubDocument(doctype)


Loading…
Cancel
Save