在所有兼容的瀏覽器(包括Chrome/Safari瀏覽器),document.doctype
也返回DocumentType
對象。以下代碼可用於生成有效的DOCTYPE字符串。
var node = document.doctype;
var html = "<!DOCTYPE "
+ node.name
+ (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '')
+ (!node.publicId && node.systemId ? ' SYSTEM' : '')
+ (node.systemId ? ' "' + node.systemId + '"' : '')
+ '>';
此方法返回正確的字符串爲valid (HTML5) doctypes,例如:
<!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">
的代碼的說明:
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
值得注意的是,沒有DOCTYPE的文檔具有'document.doctype === null'。 – 2012-12-15 23:55:04