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
广告