Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get DocType of an HTML as string with Javascript

Tags:

javascript

dom

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!

like image 223
matte Avatar asked May 22 '11 15:05

matte


People also ask

How do you pass a HTML code into a string?

click(function(){ var text = $("#tab"). html(); // taking the content var res = text.

What is parseHTML in Javascript?

parseHTML uses native methods to convert the string to a set of DOM nodes, which can then be inserted into the document. These methods do render all trailing or leading text (even if that's just whitespace).

How do you show DOCTYPE in HTML?

All HTML documents must start with a <!DOCTYPE> declaration. The declaration is not an HTML tag. It is an "information" to the browser about what document type to expect.

What is DOCTYPE in Javascript?

The doctype property returns a document's doctype (as a DocumentType object). The doctype property returns null if the document has no doctype. The doctype property is read-only. The doctype.name property returns the name of the doctype.


2 Answers

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 
like image 66
Rob W Avatar answered Oct 04 '22 02:10

Rob W


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); 
like image 44
Scott Avatar answered Oct 04 '22 02:10

Scott