title: Executing <script> elements inserted with .innerHTML
body: <p>I've got a script that inserts some content into an element using <code>innerHTML</code>.</p>
  
  <p>The content could for example be:</p>
  
  <pre><code>&lt;script type="text/javascript"&gt;alert('test');&lt;/script&gt;
  &lt;strong&gt;test&lt;/strong&gt;
  </code></pre>
  
  <p>Problem is that the code inside the <code>&lt;script&gt;</code> tag doesn't get executed.
  I googled it a bit but there were no apparent solutions. If I inserted the content using jQuery <code>$(element).append(content);</code>the script parts got <code>eval</code>'d before being injected into the DOM.</p>
  
  <p>Has anyone got a snippet of code that executes all the <code>&lt;script&gt;</code> elements? The jQuery code was a bit complex so I couldn't really figure out how it was done.</p>
  
  <p><strong>Edit</strong>:</p>
  
  <p>By peeking into the jQuery code I've managed to figure out how jQuery does it, which resulted in the following code:</p>
  
  <pre><code>Demo:
  &lt;div id="element"&gt;&lt;/div&gt;
  
  &lt;script type="text/javascript"&gt;
    function insertAndExecute(id, text)
    {
      domelement = document.getElementById(id);
      domelement.innerHTML = text;
      var scripts = [];
  
      ret = domelement.childNodes;
      for ( var i = 0; ret[i]; i++ ) {
        if ( scripts &amp;&amp; nodeName( ret[i], "script" ) &amp;&amp; (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
              scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
          }
      }
  
      for(script in scripts)
      {
        evalScript(scripts[script]);
      }
    }
    function nodeName( elem, name ) {
      return elem.nodeName &amp;&amp; elem.nodeName.toUpperCase() === name.toUpperCase();
    }
    function evalScript( elem ) {
      data = ( elem.text || elem.textContent || elem.innerHTML || "" );
  
      var head = document.getElementsByTagName("head")[0] || document.documentElement,
      script = document.createElement("script");
      script.type = "text/javascript";
      script.appendChild( document.createTextNode( data ) );
      head.insertBefore( script, head.firstChild );
      head.removeChild( script );
  
      if ( elem.parentNode ) {
          elem.parentNode.removeChild( elem );
      }
    }
  
    insertAndExecute("element", "&lt;scri"+"pt type='text/javascript'&gt;document.write('This text should appear as well.')&lt;/scr"+"ipt&gt;&lt;strong&gt;this text should also be inserted.&lt;/strong&gt;");
  &lt;/script&gt;
  </code></pre>