I'm new to JavaScript and HTML5 and today I was playing with createHTMLDocument() and I ran into a frustrating problem. I got the following snippet from Mozilla's site:
<script>
function makeDocument() {
var frame = document.getElementById("theFrame");
var doc = document.implementation.createHTMLDocument("New Document");
var p = doc.createElement("p");
p.innerHTML = "This is a new paragraph.";
try {
doc.body.appendChild(p);
} catch(e) {
console.log(e);
}
var destDocument = frame.contentDocument;
var srcNode = doc.documentElement;
var newNode = destDocument.importNode(srcNode, true);
destDocument.replaceChild(newNode, destDocument.documentElement);
console.log(destDocument.readyState);
}
</script>
<body>
<p>Click <a href="javascript:makeDocument()">here</a> to create a new document and insert it below.</p>
<iframe id="theFrame" src="about:blank" />
</body>
It works as expected. The text is put into the doc and the expected readyState, "complete", is written to the console.
But then I rejiggered the code so that makeDocument
ran automatically on load, like so:
<div>
<iframe id="frame" src="about:blank"> </iframe>
</div>
<script>
function makeDocument() {
var frame = document.getElementById("frame");
var doc = document.implementation.createHTMLDocument("New Document");
var p = doc.createElement("p");
p.innerHTML = "This is a new paragraph.";
try {
doc.body.appendChild(p);
} catch(e) {
console.log(e);
}
var destDocument = frame.contentDocument;
var srcNode = doc.documentElement;
var newNode = destDocument.importNode(srcNode, true);
destDocument.replaceChild(newNode, destDocument.documentElement);
console.log(destDocument.readyState);
}
makeDocument();
</script>
But when this is run the text is not added to the document and the document's readyState is "uninitialized." I'm sure I'm making some stupid mistake. Any ideas?