How To Detect Doctype With Javascript

I had an interesting problem recently where I actually had a need to detect which doctype a page was using, and run some css depending on which HTML version was being used (the publicId property). It took me a long time to figure out how to do this, since it is not done very often. The solution I found at first only worked for firefox, but I needed it to work for IE. I finally found a solution that works in ie.

Here’s the solution that only works in firefox:

The correct way to get the doctype publicId (which works in firefox) is:

[code lang="javascript"]var pubid = document.doctype.publicId;[/code]

The example above saves a reference to the publicId of the doctype. So if we were on a page with an XHTML 1.0 Strict doctype, the pubid variable would have the value -//W3C//DTD XHTML 1.0 Strict//EN.

Here’s the solution that works in all versions of ie, and the full code for what I needed to do:

[code lang="javascript"]
//this script finds ie browsers using html4 doctype and then does a fix for input field height
var findDOC = document.all[0].text;//gets doctype, works in ie
if (navigator.appName == "Microsoft Internet Explorer" && findDOC = '') {
var inputs = document.getElementsByTagName("input");
for (var i = 0; i
if(inputs[i].getAttribute("className", "affiliate_submit")) {
inputs[i].setAttribute("className", "affiliate_submit");
else{inputs[i].setAttribute("className", "html4fix");}

The key piece of this code is
[code lang="javascript"]document.all[0].text[/code] which is the only way to get the entire contents of the doctype in ie. IE can get the doctype, but it can't get the publicId (which is the information that contains which version of HTML is being used). Since I needed the publicId, I had to use this method.

The code above searches for all ie browsers, and then gets the doctype publicId. If the publicId is using HTML4, then I run some code to add a special css class for this scenario only.

More resources on this:
and here

This entry was posted in Javascript, Uncategorized, ie6, ie7, ie8 and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>