Dynamically insert an HTML string into a HEAD document

I need to insert an HTML string into the tag of the <head>current DOM document, one of the ways is: you create a div element, fill it innerHTML, copy by element to your <head>element. But these methods do not work in IE / Opera for the reasons given below, although in FF3 and methods below work well, and the browser handles the added elements STYLE / SCRIPT.

Is there any other way to insert a string directly into <head>and process these elements?


(Why they do not work in IE / Opera)

Method 1 - Fail because innerHTML cannot parse / ignore META, STYLE, SCRIPT elements in a 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]);
}

2 - , STYLE/ SCRIPT

 document.getElementsByTagName("head")[0].innerHTML = htmlStr
 // although this populates the <head> tag successfully
+3
1

, . (node.nodeType === 3) htmlStr :

var insertHtml = function(parentElem, htmlStr){

   var frag = document.createDocumentFragment();
   var temp = document.createElement('div');
   temp.innerHTML = "hack" + htmlStr;

   while (temp.firstChild) {
       if (temp.firstChild.nodeType === 1) {
            // add only element nodes
            frag.appendChild(temp.firstChild);
       } else {
            // remove the hack string
            temp.removeChild(temp.firstChild);
       }
   }

   parentElem.insertBefore(frag, parentElem.childNodes[0]);
}
+2

Source: https://habr.com/ru/post/1707683/


All Articles