10

Is the doctype part of the DOM, and if so, is there a good cross-browser way to read it? I'm not trying to do anything fancy. I just want to access the doctype information from within some JavaScript code. Read-only access is fine.

user241761
  • 103
  • 1
  • 4

2 Answers2

10

document.doctype seems to be the (read-only) property you're looking for.

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
  • 4
    Specifically, the optional `DocumentType` node is a `childNode` of `Document`, just as the root `documentElement` and any `Comment` nodes outside the root are. – bobince Jan 01 '10 at 00:08
  • Thank you, Alex. bobince, the comment you left is also very informative. – user241761 Jan 01 '10 at 00:20
  • 3
    Yeah, IE mis-parses the doctype as a comment. You can still find it through the `childNodes` list and read the content of the declaration as the comment's `data`, but you can't tell for sure that it wasn't actually a comment, and IE discards the leading and trailing two characters, assuming they're both going to be `--`. Ah, IE, bless it... – bobince Jan 10 '10 at 00:40
  • 4
    Is it possible to get `document.doctype` as a string somehow? And I don’t mean this one: `"[object DocumentType]"` – Mathias Bynens Jan 10 '11 at 15:56
  • +1 for Mathias's question. Is it posibl to get document.doctype as a whole doctype string both in FF, IE, Chrome and Webkit? Or should this be a separate question? – matte May 22 '11 at 15:31
2

If you're inspecting the DOCTYPE to determine if you're in quirksmode or not, this is known to be cross-browser:

document.compatMode; // returns either "BackCompat" or "CSS1Compat"

So you can do:

var quirksmode = document.compatMode == "BackCompat";
jpsimons
  • 27,382
  • 3
  • 35
  • 45
  • This isn't working completely either. IE thinks a simple (no DTD or anything) means the page is CSS1Compat. God how I loathe IE. – Alkanshel May 05 '11 at 23:42