Skip to content

Instantly share code, notes, and snippets.

@os0x
Created September 30, 2009 20:54
Show Gist options
  • Save os0x/198443 to your computer and use it in GitHub Desktop.
Save os0x/198443 to your computer and use it in GitHub Desktop.
文字列からHTMLDocumentをつくるスニペット/for Firefox3.5,Opera10,Google Chrome4
// via http://github.com/hatena/hatena-bookmark-xul/blob/master/chrome/content/common/05-HTMLDocumentCreator.js
function createDocumentFromString(source){
var doc;
if (document.implementation.createHTMLDocument) {
doc = document.implementation.createHTMLDocument('title');
} else {
doc = document.cloneNode(false);
if (doc) {
doc.appendChild(doc.importNode(document.documentElement, false));
} else {
doc = document.implementation.createDocument(null, 'html', null);
}
}
var range = document.createRange();
range.selectNodeContents(document.documentElement);
var fragment = range.createContextualFragment(source);
var headChildNames = {title: true, meta: true, link: true, script: true, style: true, /*object: true,*/ base: true/*, isindex: true,*/};
var child, head = doc.getElementsByTagName('head')[0] || doc.createElement('head'),
body = doc.getElementsByTagName('body')[0] || doc.createElement('body');
while ((child = fragment.firstChild)) {
if (
(child.nodeType === doc.ELEMENT_NODE && !(child.nodeName.toLowerCase() in headChildNames)) ||
(child.nodeType === doc.TEXT_NODE &&/\S/.test(child.nodeValue))
)
break;
head.appendChild(child);
}
body.appendChild(fragment);
doc.documentElement.appendChild(head);
doc.documentElement.appendChild(body);
return doc;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment