HTML DOM doctype 属性

htmlweb developmentfront end technology更新于 2024/6/1 14:36:17

HTML DOM doctype 属性返回与当前 HTML 文档关联的 DTD(文档类型声明)。它是一个只读属性。它以 DocumentType 对象的形式返回 doctype 名称。如果给定文档未指定 DTD,则返回 null。

语法

以下是 doctype 属性的语法 −

document.doctype

示例

让我们看一个 doctype 属性的示例 −

<!DOCTYPE html>
<html>
<body>
<h1>doctype property example</h1>
<button onclick="getDoctype()">GET DOCTYPE</button>
<p id="Sample"></p>
<script>
   function getDoctype() {
      var doc = document.doctype.name;
      document.getElementById("Sample").innerHTML ="The doctype for this HTML document is: "+doc;
   }
</script>
</body>
</html>

输出

这将产生以下输出 −

点击"获取文档类型"按钮 −

我们首先将 HTML 文档的 DTD(文档类型定义)设置为 HTML。这将确保该文档被渲染为 HTML 文档 −

<!DOCTYPE html>

然后,我们创建了一个按钮"GET DOCTYPE",当用户点击该按钮时,它将执行 getDoctype() 函数 −

<button onclick="getDoctype()">GET DOCTYPE</button>

getDoctype() 方法使用文档的 doctype 属性 name 值并将其赋值给变量 doc。然后,变量 doc 将显示在 ID 为"Sample"的段落中,其 innerHTML 属性将设置为预期文本 −

function getDoctype() {
   var doc = document.doctype.name;
   document.getElementById("Sample").innerHTML ="The doctype for this HTML document is: "+doc;
}

相关文章


有用资源