Dom Prop Document Doctype
## XML DOM doctype Property
The `doctype` property returns the Document Type Declaration (DTD) associated with the current XML or HTML document.
For XML documents without a DTD, or HTML5 documents that do not explicitly define one, this property returns `null`.
This property provides direct access to the `DocumentType` object, which is a child node of the `Document` node.
---
## Syntax
```javascript
documentObject.doctype
```
### Return Value
* **`DocumentType` Object**: Represents the document type declaration (e.g., `` or ``).
* **`null`**: Returned if there is no DTD associated with the document.
---
## Technical Details
| Feature | Description |
| :--- | :--- |
| **DOM Version** | DOM Level 1 Core |
| **Read/Write** | Read-only |
| **Return Type** | `DocumentType` object or `null` |
---
## Code Examples
### Example 1: Accessing the DocumentType Object
The following code snippet loads an XML file containing an internal DTD (`note_internal_dtd.xml`) using a custom helper function `loadXMLDoc()`, and retrieves its `doctype` property.
```javascript
// Load the XML document
var xmlDoc = loadXMLDoc("note_internal_dtd.xml");
// Retrieve the doctype property
var docTypeObj = xmlDoc.doctype;
// Output the object representation
console.log(docTypeObj);
// Output in browser console:
```
### Example 2: Inspecting DocumentType Properties
Once you have retrieved the `DocumentType` object, you can access its properties, such as `name`, `publicId`, and `systemId`.
Given an XML document with the following DTD declaration:
```xml
```
You can inspect its properties using JavaScript:
```javascript
var xmlDoc = loadXMLDoc("note_internal_dtd.xml");
var dtd = xmlDoc.doctype;
if (dtd !== null) {
console.log("Document Type Name: " + dtd.name); // Output: "note"
console.log("System Identifier: " + dtd.systemId); // Output: "Note.dtd"
console.log("Public Identifier: " + dtd.publicId); // Output: "" (empty string if not specified)
} else {
console.log("No DTD found for this document.");
}
```
---
## Considerations and Best Practices
1. **Read-Only Property**: The `doctype` property is read-only. You cannot programmatically assign a new DTD to an existing document using `document.doctype = ...`.
2. **HTML5 Behavior**: In modern HTML5 documents, `document.doctype` will return ``. You can access its name via `document.doctype.name`, which returns `"html"`.
3. **Null-Safety**: Always perform a null check (`if (document.doctype !== null)`) before attempting to access properties on the returned object to prevent runtime errors in documents that lack a DTD.
YouTip