Get DocType of an HTML as string with Javascript

You can also use this one liner to get the current doctype. This will work in any modern browser and IE 9 and higher.

new XMLSerializer().serializeToString(document.doctype);

function get_doctype()
{
    var doctype = 
    '<!DOCTYPE ' + 
    document.doctype.name +
    (document.doctype.publicId?' PUBLIC "' +  document.doctype.publicId + '"':'') +
    (document.doctype.systemId?' "' + document.doctype.systemId + '"':'') + '>';
    return doctype;
}

In all compliant browsers (including Chrome/Safari), document.doctype also returns a DocumentType object. The following code can be used to generate a valid DOCTYPE string.

var node = document.doctype;
var html = "<!DOCTYPE "
         + node.name
         + (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '')
         + (!node.publicId && node.systemId ? ' SYSTEM' : '') 
         + (node.systemId ? ' "' + node.systemId + '"' : '')
         + '>';

This method returns the correct string for valid (HTML5) doctypes, eg:

  • <!DOCTYPE html>
  • <!DOCTYPE html SYSTEM "about:legacy-compat">
  • <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">

Explanation of the code:

node.name      # Holds the name of the root element, eg: HTML / html
node.publicId  # If this property is present, then it's a public document type.
               #>Prefix PUBLIC
!node.publicId && node.systemId
               # If there's no publicId, but a systemId, prefix SYSTEM
node.systemId  # Append this if present

Tags:

Javascript

Dom