我知道我可以通过 document.doctype
访问 doctype 对象或 document.childNodes[0]
但我的问题是将文档类型作为字符串获取。我可以通过调用 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 对象。
有没有办法在所有浏览器中获取 doctype 字符串,就像在 chrome 和 safari 中一样?
谢谢!
最佳答案
在所有兼容的浏览器(包括 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
关于javascript - 使用 Javascript 将 HTML 的 DocType 获取为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6088972/