JavaScript中的document.doctype


本文作者: jsweibo

本文链接: https://jsweibo.github.io/2020/06/07/JavaScript%E4%B8%AD%E7%9A%84document-doctype/

摘要

本文主要讲述了:

  1. 作用
  2. getDoctypeHTML

正文

作用

指向文档类型声明节点

若文档类型声明节点不存在,返回null

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
// <!DOCTYPE html>
console.log(document.doctype);

// "object"
console.log(typeof document.doctype);
</script>
</body>
</html>

getDoctypeHTML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function getDoctypeHTML(doctype) {
if (doctype) {
let output = '<!DOCTYPE';

if (doctype.name) {
output += ' ' + doctype.name;
}
if (doctype.publicId) {
output += ' PUBLIC "' + doctype.publicId + '"';
}
if (doctype.systemId) {
output += ' "' + doctype.systemId + '"';
}
output += '>';

return output;
} else {
return '';
}
}

console.log(getDoctypeHTML(document.doctype));

参考资料

本文作者: jsweibo

本文链接: https://jsweibo.github.io/2020/06/07/JavaScript%E4%B8%AD%E7%9A%84document-doctype/


本文对你有帮助?请支持我


支付宝
微信