HTML DOM head 属性
htmlweb developmentfront end technology更新于 2025/9/24 7:08:17
HTML DOM head 属性与 HTML <head> 元素关联。它用于返回 <head> 元素。如果有多个 head 元素,则返回第一个 head 元素。它是一个只读属性。
语法
以下是 head 属性 − 的语法
document.head
示例
让我们来看一个 HTML DOM head 属性的示例 −
<!DOCTYPE html>
<html>
<head>
<title>My title</title>
</head>
<body>
<h1>head property example</h1>
<p>Get this document title by clicking on the below button</p>
<button onclick="getTitle()">Get Title</button>
<p id="Sample"></p>
<script>
function getTitle() {
var x = document.head.firstElementChild.innerHTML;
document.getElementById("Sample").innerHTML = "The title of this document is: "+x;
}
</script>
</body>
</html>
输出
这将产生以下输出 −

点击"获取标题"按钮 −

在上面的例子中 −
我们首先创建了一个 <head> 元素,其中包含一个 <title> 元素,用于指定此网页的标题 −
<head> <title>My title</title> </head>
然后,我们创建一个按钮"获取标题",当用户点击该按钮时,它将执行 getTitle() 方法。
<button onclick="getTitle()">Get Title</button>
getTitle() 方法使用文档的 head 属性获取 head 元素,并使用 firstElementChild 属性获取其第一个子元素,在本例中即为 <title> 元素。
然后,我们使用 title 元素的 innerHTML 属性获取其中的文本,并将其显示在 id 为"Sample"的段落中 −
function getTitle() {
var x = document.head.firstElementChild.innerHTML;
document.getElementById("Sample").innerHTML = "The title of this document is: "+x;
}
相关文章
有用资源
html 参考教程 - 该教程包含有关 html 的更多信息:https://www.cainiaomax.com/html/

