使用Javascript获取HTML的文档类型字符串

37

我知道可以通过document.doctypedocument.childNodes [0]来访问 doctype 对象,但我的问题是如何将 doctype 作为字符串获取。在 Chrome 和 Safari 中,我可以通过调用document.doctype 来实现这一点,它返回<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">。然而,在 Firefox 中,调用document.doctype会返回 DocumentType 对象。

是否有一种方法可以在像 Chrome 和 Safari 一样的所有浏览器中获取 doctype 字符串呢?

谢谢!

5个回答

80
在所有兼容的浏览器中(包括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 + '"' : '')
         + '>';

这个方法返回有效的(HTML5) doctype对应的正确字符串,例如:
  • <!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

16
值得注意的是,没有 DOCTYPE 的文档会使 document.doctype === null - Brad Koch

56

这将添加 xmlns 属性。 - vee

3
function get_doctype()
{
    var doctype = 
    '<!DOCTYPE ' + 
    document.doctype.name +
    (document.doctype.publicId?' PUBLIC "' +  document.doctype.publicId + '"':'') +
    (document.doctype.systemId?' "' + document.doctype.systemId + '"':'') + '>';
    return doctype;
}

1

这是你在寻找的吗?

alert(document.doctype.publicId);

只返回了“-//W3C//DTD HTML 4.01//EN”。我需要整个DOCTYPE。 - matte
1
也许你需要执行以下代码 --- var doc = '<!DOCTYPE '+document.doctype.name+' PUBLIC "'+document.doctype.publicId+'" "'+document.doctype.systemId+'">'; - T1000

1

DocumentType.name.publicId.systemId连接起来。类似于:

'<!DOCTYPE '+ 
  DocumentType.name+' PUBLIC "'+ //maybe you should check for publicId first
  DocumentType.publicId+'" "'+
  DocumentType.systemId+'">'

我猜这不支持HTML5? - Kendall Hopkins
@Kendall:确实有,但据我所知对于HTML5来说信息不是很详细。 - KooiInc
4
我的意思是,它应该打印 <!DOCTYPE html>,但是对于这个使用 HTML5 doctype 的页面,我得到了 <!DOCTYPE html PUBLIC "" ""> - Kendall Hopkins

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接