YouTip LogoYouTip

Prop Attr Ownerdocument

## XML DOM: ownerDocument Property (Attr Object) The `ownerDocument` property of an `Attr` (Attribute) object returns the root document element (`Document` or `XMLDocument` object) to which the attribute node belongs. This property is highly useful when you are working with multiple documents or need to access the global document context directly from a specific attribute node. --- ## Definition and Usage * **Purpose**: Returns the owner `Document` object of the attribute node. * **Return Value**: A `Document` object (or `XMLDocument` object in XML contexts), which represents the root of the document containing the node. * **Read-only**: This property is read-only. --- ## Syntax ```javascript attrObject.ownerDocument ``` ### Return Value Details * If the attribute node belongs to a document, it returns the `Document` object. * If the attribute node is newly created and has not yet been added to a document, this property will still return the `Document` object that was used to create it (e.g., via `document.createAttribute()`). * If called on a `Document` node itself, it returns `null`. --- ## Code Example The following example demonstrates how to load an XML document (`books.xml`) and retrieve the owner document of the first attribute of the first `` element. ### Sample XML File (`books.xml`) ```xml Everyday Italian Giada De Laurentiis 2005 30.00 ``` ### JavaScript Implementation ```javascript // Load the XML document const xmlDoc = loadXMLDoc("books.xml"); // Select all elements const books = xmlDoc.getElementsByTagName('book'); // Get the first attribute of the first element (category="cooking") const firstAttr = books.item(0).attributes; // Retrieve the owner document of this attribute const ownerDoc = firstAttr.ownerDocument; // Output the results document.write("Owner Document Object: " + ownerDoc + "
"); document.write("Node Name: " + ownerDoc.nodeName + "
"); document.write("Node Type: " + ownerDoc.nodeType + "
"); ``` ### Expected Output ```text Owner Document Object: Node Name: #document Node Type: 9 ``` *Note: `nodeType` value `9` corresponds to the `Node.DOCUMENT_NODE` constant.* --- ## Key Considerations 1. **Document vs. Owner Document**: While `ownerDocument` returns the root document node, it is different from the global `document` object in web browsers if you are working with an external XML document loaded via AJAX or an iframe. 2. **Context Preservation**: Even if an attribute node is detached from an element (for example, using `removeAttributeNode()`), it still retains a reference to its `ownerDocument`. 3. **Browser Compatibility**: The `ownerDocument` property is supported across all modern web browsers and complies with the W3C DOM Core standard.
← Prop Attr OwnerelementProp Attr Nodevalue β†’