HTML - DOM 文件 head 屬性



**head** 屬性與 HTML 的 <head> 元素相關聯。它用於返回 <head> 元素。如果有多個 head 元素,則它將返回第一個 <head> 元素;如果沒有 head 元素,則 HTML 會新增一個空的 <head>。這是一個只讀屬性。

語法

document.head;

返回值

它返回文件的 head 元素。

HTML DOM 文件“head”屬性的示例

下面是一些顯示 **head** 屬性用法的示例。

獲取 <head> 元素

以下示例說明了如何使用 head 屬性獲取 HTML 文件的 head 元素。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        HTML DOM document head Property
    </title>
</head>
<body>
    <button onclick="fun()">Click me</button>
    <p id="head"></p>
    <script>
        function fun() {
            let tag = document.head.tagName;
            document.getElementById("head").innerHTML = tag;
        }
    </script>
</body>
</html>

獲取 <head> 元素

以下示例說明了如何使用 head 屬性獲取 HTML 文件的 head 元素,**不包含** head 標籤。

<!DOCTYPE html>
<html lang="en">
<body>
    <p>
        This document does not have 
        any <head> element.
    </p>
    <button onclick="fun()">Click me</button>
    <p id="head"></p>
    <script>
        function fun() {
            let x = document.head.tagName;
            document.getElementById("head").innerHTML = x;
        }
    </script>
</body>
</html>

獲取 <head> 元素的另一種方法

此示例說明了如何在不使用 head 屬性的情況下獲取 head 元素。

<!DOCTYPE html>
<html lang="en">
<body>
    <button onclick="fun()">
        Click me
    </button>
    <p id="head"></p>
    <script>
        function fun() {
            let x = document.getElementsByTagName("head")[0].tagName;
            document.getElementById("head").innerHTML = x;
        }
    </script>
</body>
</html>

獲取文件的標題

以下示例說明了如何使用 head 屬性獲取文件的標題名稱。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        HTML DOM document head Property
    </title>
</head>
<body>
    <p>
        Click the button below to get the 
        Title of the document.
    </p>
    <button onclick="fun()">Click me</button>
    <p id="head"></p>
    <script>
        function fun() {
            let x = document.head.firstElementChild.innerHTML;
            document.getElementById("head").innerHTML = x;
        }
    </script>
</body>
</html>

支援的瀏覽器

屬性 Chrome Edge Firefox Safari Opera
head 是 4 是 12 是 4 是 5 是 11
html_dom_document_reference.htm
廣告