使用Javascript获取HTML的DocType作为字符串

mat*_*tte 30 javascript dom

我知道我可以通过document.doctype或访问doctype对象,document.childNodes[0]但我的问题是将doctype作为字符串.我可以通过调用document.doctype返回来在chrome和safari中执行此操作<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">.但是在Firefox中,调用document.doctype返回DocumentType对象.

有没有办法在Chrome和safari中获取所有浏览器中的doctype字符串?

谢谢!

Rob*_*b W 71

在所有兼容的浏览器(包括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 + '"' : '')
         + '>';
Run Code Online (Sandbox Code Playgroud)

此方法返回有效(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
Run Code Online (Sandbox Code Playgroud)

  • 值得注意的是没有DOCTYPE的文件有一个`document.doctype === null`. (11认同)

Sco*_*ott 48

您还可以使用此一个衬垫来获取当前的doctype.这适用于任何现代浏览器和IE 9及更高版本.

new XMLSerializer().serializeToString(document.doctype);
Run Code Online (Sandbox Code Playgroud)

  • 比接受的答案简单得多. (10认同)