os0x (owner)

Revisions

gist: 198443 Download_button fork
public
Description:
文字列からHTMLDocumentをつくるスニペット/for Firefox3.5,Opera10,Google Chrome4
Public Clone URL: git://gist.github.com/198443.git
Embed All Files: show embed
createDocumentFromString.js #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// via http://github.com/hatena/hatena-bookmark-xul/blob/master/chrome/content/common/05-HTMLDocumentCreator.js
function createDocumentFromString(source){
var doc = document.implementation.createHTMLDocument ?
document.implementation.createHTMLDocument('hogehoge') :
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.createElement('head'), body = doc.createElement('body');
while ((child = fragment.firstChild)) {
if (
(child.nodeType === Node.ELEMENT_NODE && !(child.nodeName.toLowerCase() in headChildNames)) ||
(child.nodeType === Node.TEXT_NODE &&/\S/.test(child.nodeValue))
)
break;
head.appendChild(child);
}
body.appendChild(fragment);
doc.documentElement.appendChild(head);
doc.documentElement.appendChild(body);
return doc;
}