I need to insert an HTML string into the <head>
tag of the current document DOM, one way is: you create a div element, fill its innerHTML, copy over item-by-item into your <head>
element. But these methods do not work in IE/Opera for reasons given below, though in FF3 both the below methods work perfectly, and the browser processes the added STYLE/SCRIPT elements.
Is there any other way you can insert a string directly into <head>
and have those items processed?
(Why they fail in IE/Opera)
Method 1 - Fails because innerHTML cannot parse/ignores META, STYLE, SCRIPT elements within the string
insertHtml = function(parentElem,htmlStr){
var frag = document.createDocumentFragment();
var temp = document.createElement('div');
temp.innerHTML = htmlStr;
// at this point, temp.childNodes.length=0
while (temp.firstChild) {
frag.appendChild(temp.firstChild);
}
// use native DOM methods to insert the fragment
parentElem.insertBefore(frag, parentElem.childNodes[0]);
}
Method 2 - Fails because added STYLE/SCRIPT elements do not get processed by the browser
document.getElementsByTagName("head")[0].innerHTML = htmlStr
// although this populates the <head> tag successfully