Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
53
rated 0 times [  55] [ 2]  / answers: 1 / hits: 24048  / 13 Years ago, sun, may 22, 2011, 12:00:00

I know that I can access to doctype object via document.doctype or document.childNodes[0] but my problem is getting doctype as a string. I can do this in chrome and safari by calling document.doctype which returns <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">. However in Firefox, calling document.doctype returns DocumentType object.


Is there a way to get the doctype string in all browsers as in chrome and safari?


Thanks!


More From » dom

 Answers
25

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

[#92118] Thursday, May 19, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
josh

Total Points: 391
Total Questions: 112
Total Answers: 90

Location: Aruba
Member since Fri, Jun 24, 2022
2 Years ago
josh questions
Wed, Aug 4, 21, 00:00, 3 Years ago
Mon, Aug 24, 20, 00:00, 4 Years ago
Wed, Aug 12, 20, 00:00, 4 Years ago
;