JSFiddle - React, Tailwind, and code Playground
HTML
<p>
<a href="http://stackoverflow.com/questions/7474710/can-i-load-an-entire-html-document-into-a-document-fragment-in-internet-explorer/7539198#7539198">Demo of answer provided at Stack Overflow</a>
</p>
<p>When you run this fiddle, two alerts should pop up:<br />
The first alert shows "Test", while the second dialog shows "DIV".</p>
JavaScript
//Test case
string2dom("<html><head><title>Test</title></head></html>", function(doc, destroy){
alert(doc.title); /* Alert: "Test" */
destroy();
});
var test = string2dom("<div id='secret'></div>");
alert(test.doc.getElementById("secret").tagName); /* Alert: "DIV" */
test.destroy();
/*
@param String html The string with HTML which has be converted to a DOM object
@param func callback (optional) Callback(HTMLDocument doc, function destroy)
@returns undefined if callback exists, else: Object
HTMLDocument doc DOM fetched from Parameter:html
function destroy Removes HTMLDocument doc. */
function string2dom(html, callback){
/* Sanitise the string */
html = html.replace(/<script[^>]*?>\s*\/\/\s*<\[CDATA\[[\S\s]*?]]>\s*<\/script\s*>/gi, "")
.replace(/<script[\S\s]+?<\/script\s*>/gi,"")
.replace(/(<i?frame)([^>]*)>/gi, function(string, tag, attr){
/* Input: <iframe src=..> output: <iframe data-src=..> */
return tag + attr.replace(/src=/gi, "data-src=")
})
.replace(/ o([nN])/g," o$1").replace(/ O([Nn])/g," O$1");
/* Create an IFrame */
var iframe = document.createElement("iframe");
iframe.style.display = "none";
document.body.appendChild(iframe);
var doc = iframe.contentDocument || iframe.contentWindow.document;
doc.open();
doc.write(html);
doc.close();
function destroy(){
iframe.parentNode.removeChild(iframe);
}
if(callback) callback(doc, destroy);
else return {"doc": doc, "destroy": destroy};
}