假设(在 IE8 中)我们有一个文档
。
现在通常我们可以假设 document.childNodes[0]
是文档类型。所以
var doctype = document.childNodes[0]
现在我们如何确认而不是假定它是文档类型?
doctype.nodeType === Node.COMMENT_NODE;
doctype.tagName === "!"; // same as a comment
doctype.data.indexOf("DOCTYPE ") > -1; // same as any comment containing the word DOCTYPE.
doctype === document.doctype; // false, document.doctype is undefined in IE8
除了假设之外,我应该如何知道给定节点是否为文档类型?
对于那些不熟悉 DOM4 的人,请查看 DocumentType
DOM-shim通过返回 document.childNodes[0]
document.doctype
最佳答案
我发现在 IE7 和 IE8 中 .innerHTML
评论属性始终是完整的"<!--comment here-->"
对于文档类型节点,它是 ""
.即使是空评论,.innerHTML
是"<!---->"
所以基于此我创建了:
function isDocType(node) {
return node && (
node.nodeType === 10 || (node.nodeType === 8 && "innerHTML" in node && node.innerHTML === ""));
}
带有测试页:
<!-- comment1 -->
<!-- comment2 -->
<!---->
<!-- -->
<!-- <!DOCTYPE html> -->
通过 isDocType
运行文档类型和注释给出:
LOG: true
LOG: false
LOG: false
LOG: false
LOG: false
LOG: false
关于html - 如何检查 DOM 节点是否是表示文档类型声明的节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7933344/