DOMImplementation: createHTMLDocument() 方法
DOMImplementation.createHTMLDocument() 方法建立一個新的 HTML Document。
語法
js
createHTMLDocument()
createHTMLDocument(title)
引數
title可選-
一個包含新 HTML 文件標題的字串。
返回值
一個新建立的 HTML Document 物件。
示例
此示例建立了一個新的 HTML 文件,並將其插入到當前文件中的一個 <iframe> 中。
此示例的 HTML 程式碼如下:
html
<button id="create-doc">Create new document</button>
<iframe id="theFrame" src="about:blank"></iframe>
makeDocument() 的 JavaScript 實現如下:
js
function makeDocument() {
const frame = document.getElementById("theFrame");
const doc = document.implementation.createHTMLDocument("New Document");
const p = doc.createElement("p");
p.textContent = "This is a new paragraph.";
try {
doc.body.appendChild(p);
} catch (e) {
console.log(e);
}
// Copy the new HTML document into the frame
const destDocument = frame.contentDocument;
const srcNode = doc.documentElement;
const newNode = destDocument.importNode(srcNode, true);
destDocument.replaceChild(newNode, destDocument.documentElement);
}
document.getElementById("create-doc").addEventListener("click", makeDocument);
該程式碼負責建立新的 HTML 文件並向其中插入一些內容。createHTMLDocument() 會構造一個新 HTML 文件,其 <title> 為 "New Document"。然後,我們建立一個帶有簡單內容的新段落元素,接著將這個新段落插入到新文件中。
destDocument 儲存了 frame 的 contentDocument;這是我們將要注入新內容的文件。接下來的兩行處理將我們新文件的內容匯入到新文件的上下文中。最後,destDocument.replaceChild 實際上用新文件的內容替換了 frame 的內容。
返回的文件預先構建了以下 HTML:
html
<!doctype html>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<title>title</title>
</head>
<body>
…
</body>
</html>
規範
| 規範 |
|---|
| DOM # ref-for-dom-domimplementation-createhtmldocument① |
瀏覽器相容性
載入中…
另見
- 它所屬的
DOMImplementation介面。