Skip to content

Instantly share code, notes, and snippets.

@cho45
Created January 20, 2009 12:43
Show Gist options
  • Save cho45/49453 to your computer and use it in GitHub Desktop.
Save cho45/49453 to your computer and use it in GitHub Desktop.
createHTMLDocument
function createHTMLDocument (title) {
// Firefox doesn't have createHTMLDocument
if (!document.implementation.createHTMLDocument) {
// Maybe this is the best way to create HTMLDocument, but not worked in any browser...
// var html4dt = document.implementation.createDocumentType("HTML", "-//W3C//DTD HTML 4.01//EN", "http://www.w3.org/TR/html4/strict.dtd");
// var d = document.implementation.createDocument("", "HTML", html4dt);
// return d;
// In Firefox
// Try to create HTMLDocument from XSLT with <xsl:output method='html'/>
if (typeof XSLTProcessor != "undefined") {
// Using createContextualFragment to avoid https://bugzilla.mozilla.org/show_bug.cgi?id=212362
// (problem of URI of document created by DOMParser and XSLT URI)
var x = new XSLTProcessor();
var t = [
"<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>",
"<xsl:output method='html'/>",
"<xsl:template match='/'>",
"<html><head><title>", title, "</title></head><body/></html>",
"</xsl:template>",
"</xsl:stylesheet>",
].join("");
var d = document.implementation.createDocument("", "nice-boat", null);
var r = d.createRange();
r.selectNodeContents(d.documentElement);
try {
d.documentElement.appendChild(r.createContextualFragment(t));
} catch(e) {
// TODO: Firefox 2.0.0.10 does not work on this part.
return null;
}
x.importStylesheet(d.documentElement.firstChild);
var ret = x.transformToDocument(d);
// if the returned value is not HTMLDocument, this function returns null.
return ret.body ? ret : null;
} else {
return null;
}
} else {
return document.implementation.createHTMLDocument(title);
}
}
@matthewrobb
Copy link

How does this work with IE? Is there a solution for supporting this functionality in IE(6,7,8,+) ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment