HTML - DOM 元素 ownerDocument 屬性



ownerDocument 屬性提供包含特定元素的文件節點的物件。

語法

element.ownerDocument;

返回值

ownerDocument 屬性返回包含特定元素的文件物件。

HTML DOM 元素 'ownerDocument' 屬性示例

以下是一些示例,展示了 'ownerDocument' 屬性的使用,以便更好地理解。

獲取 ownerDocument 的節點型別

此示例演示如何使用 ownerDocument 屬性訪問 <div> 元素的 ownerDocument。單擊按鈕後,它會在 <div> 元素中顯示 ownerDocument 的節點型別。

<!DOCTYPE html>
<html lang="en">
<head> 
  <title>
    HTML DOM Element ownerDocument Property
  </title>
</head>

<body>
    <h1>HTML - DOM Element</h1>
    <h2> OwnerDocument Property</h2>
    <p>Click button to get owner document of 
    	the <div> element
    </p>
    
    <div id="exdiv">
        <p>Paragraph inside a div.</p>
    </div>

    <button onclick="showOwnerDocumentType()">
    	Show Owner Document Type
    </button>
    <hr>
    <div id="output"></div>

    <script>
        function showOwnerDocumentType() {
            var ex=document.getElementById('exdiv');
            var ownerDoc = ex.ownerDocument;
            var ownd = ownerDoc.nodeType;

            var otd = document.getElementById('output');
            otd.textContent = 
            `Owner Document Type: ${ownd}`;
        }
    </script>
</body>

</html>  

使用 ownerDocument 屬性訪問文件標題

此示例演示如何使用 ownerDocument 屬性訪問元素所屬文件的標題。它包含一個<div> 元素,用於顯示輸出,以及一個按鈕,單擊該按鈕後,將顯示擁有該元素的文件的標題。

<!DOCTYPE html>
<html lang="en">
<head> 
  <title>
    HTML DOM Element ownerDocument Property
  </title>
</head>

<body>
    <h1>HTML - DOM Element</h1>
    <h2>OwnerDocument Property</h2>
    <p>Click button to get the title of 
        the document that owns the element..
    </p>

    <div id="ex">
        <p>
            This paragraph is inside a div element.
        </p>
    </div>
    
    <button onclick="showOwnerDocument()">
    	Show Owner Document
    </button>
    
    <div id="ot"></div>
    
    <script>
        function showOwnerDocument() {
            var exDiv = document.getElementById('ex');
            var ownerDoc = exDiv.ownerDocument;
            var ownerTitle = ownerDoc.title;
            var message = 
            `Owner Document Title: ${ownerTitle}`;

            // Displaying result in output div
            var ot = document.getElementById('ot');
            ot.textContent = message;
        }
    </script>
</body>

</html>  

支援的瀏覽器

屬性 Chrome Edge Firefox Safari Opera
ownerDocument
html_dom_element_reference.htm
廣告