JavaScript Snippet – Get DOCTYPE As String

You can’t really parse document.doctype as an object,
but lucky the doctype format is well defined,
so we can blend together the parts & strings to render an accurate doctype.

(function(EMPTY_STRING, SPACE, doctype, tmp){ "use strict";
  function is_empty(value){ return "undefined" === typeof value || null === value || EMPTY_STRING === value; }

  if(true === is_empty(doctype)) return EMPTY_STRING; /* non-existing DOCTYPE or an empty one */
  return "<!DOCTYPE##NAME####PUBLIC####PUBLICID####SYSTEM####SYSTEMID####INTERNALSUBSET##>"
          .replace("##NAME##",            true === is_empty(doctype.name)           ? EMPTY_STRING : SPACE + doctype.name                  )
          .replace("##PUBLIC##",          true === is_empty(doctype.publicId)       ? EMPTY_STRING : SPACE + "PUBLIC"                      )
          .replace("##PUBLICID##",        true === is_empty(doctype.publicId)       ? EMPTY_STRING : SPACE + '"' + doctype.publicId + '"'  )
          .replace("##SYSTEM##",          true === is_empty(doctype.systemId)
                                          || false === is_empty(doctype.publicId)   ? EMPTY_STRING : SPACE + "SYSTEM"                      )
          .replace("##SYSTEMID##",        true === is_empty(doctype.systemId)       ? EMPTY_STRING : SPACE + '"' + doctype.systemId + '"'  )
          .replace("##INTERNALSUBSET##",  true === is_empty(doctype.internalSubset) ? EMPTY_STRING : SPACE + '[' + doctype.systemId + ']'  )
        ;
}(
 ""
," "
,self.document.doctype
,undefined
));

some websites might have the top-root part of the document (the doctype.name) different, by letter-case,
for example <!DOCTYPE HTML... vs. the output of <!DOCTYPE html...,
the standard is lower-case (html), but regardless, this part is not case-sensitive so it does not matter.

…You can always run get the exact string by fetching the document..

function get_doctype_by_xhr(callback){
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function(){
    if(XMLHttpRequest.DONE !== xhr.status) return;
    callback(xhr.response.match(/(^.*)\<html/im));
  };
  xhr.open("GET", location.toString(), true);
  xhr.overrideMimeType("text/plain;charset=UTF-8");
  xhr.responseType = "text";
  xhr.send()
}

get_doctype_by_xhr(function(doctype_text){
  document.title = doctype_text;
});

..but really.. don’t do that.. ;)

Leave a Reply