JavaScript Frustrating innerHTML Issue [duplicate]

I tried to load some scripts into a page using innerHTML on a <div>. It appears that the script loads into the DOM, but it is never executed (at least in Firefox and Chrome). Is there a way to have scripts execute when inserting them with innerHTML?

Sample code:

<!DOCTYPE html>
  <body onload="document.getElementById('loader').innerHTML = '<script>alert(\'hi\')<\/script>'">
    Shouldn't an alert saying 'hi' appear?
    <div id="loader"></div>

You have to use eval() to execute any script code that you've inserted as DOM text.

MooTools will do this for you automatically, and I'm sure jQuery would as well (depending on the version. jQuery version 1.6+ uses eval). This saves a lot of hassle of parsing out <script> tags and escaping your content, as well as a bunch of other "gotchas".

Generally if you're going to eval() it yourself, you want to create/send the script code without any HTML markup such as <script>, as these will not eval() properly.


Here is a very interesting solution to your problem:

So use this instead of script tags:

<img src="empty.gif" onload="alert('test');this.parentNode.removeChild(this);" />


You can create script and then inject the content.

var g = document.createElement('script');
var s = document.getElementsByTagName('script')[0];
g.text = "alert(\"hi\");"
s.parentNode.insertBefore(g, s);

This works in all browsers :)


I used this code, it is working fine

var arr = MyDiv.getElementsByTagName('script')
for (var n = 0; n < arr.length; n++)
    eval(arr[n].innerHTML)//run script inside div

For anyone still trying to do this, no, you can't inject a script using innerHTML, but it is possible to load a string into a script tag using a Blob and URL.createObjectURL.

I've created an example that lets you run a string as a script and get the 'exports' of the script returned through a promise:

function loadScript(scriptContent, moduleId) {
    // create the script tag
    var scriptElement = document.createElement('SCRIPT');

    // create a promise which will resolve to the script's 'exports'
    // (i.e., the value returned by the script)
    var promise = new Promise(function(resolve) {
        scriptElement.onload = function() {
            var exports = window["__loadScript_exports_" + moduleId];
            delete window["__loadScript_exports_" + moduleId];

    // wrap the script contents to expose exports through a special property
    // the promise will access the exports this way
    var wrappedScriptContent =
        "(function() { window['__loadScript_exports_" + moduleId + "'] = " + 
        scriptContent + "})()";

    // create a blob from the wrapped script content
    var scriptBlob = new Blob([wrappedScriptContent], {type: 'text/javascript'});

    // set the id attribute = "__loadScript_module_" + moduleId;

    // set the src attribute to the blob's object url 
    // (this is the part that makes it work)
    scriptElement.src = URL.createObjectURL(scriptBlob);

    // append the script element

    // return the promise, which will resolve to the script's exports
    return promise;


function doTheThing() {
    // no evals
    loadScript('5 + 5').then(function(exports) {
         // should log 10

I've simplified this from my actual implementation, so no promises that there aren't any bugs in it. But the principle works.

If you don't care about getting any value back after the script runs, it's even easier; just leave out the Promise and onload bits. You don't even need to wrap the script or create the global window.__load_script_exports_ property.


Here is a recursive function to set the innerHTML of an element that I use in our ad server:

// o: container to set the innerHTML
// html: html text to set.
// clear: if true, the container is cleared first (children removed)
function setHTML(o, html, clear) {
    if (clear) o.innerHTML = "";

    // Generate a parseable object with the html:
    var dv = document.createElement("div");
    dv.innerHTML = html;

    // Handle edge case where innerHTML contains no tags, just text:
    if (dv.children.length===0){ o.innerHTML = html; return; }

    for (var i = 0; i < dv.children.length; i++) {
        var c = dv.children[i];

        // n: new node with the same type as c
        var n = document.createElement(c.nodeName);

        // copy all attributes from c to n
        for (var j = 0; j < c.attributes.length; j++)
            n.setAttribute(c.attributes[j].nodeName, c.attributes[j].nodeValue);

        // If current node is a leaf, just copy the appropriate property (text or innerHTML)
        if (c.children.length == 0)
            switch (c.nodeName)
                case "SCRIPT":
                    if (c.text) n.text = c.text;
                    if (c.innerHTML) n.innerHTML = c.innerHTML;
        // If current node has sub nodes, call itself recursively:
        else setHTML(n, c.innerHTML, false);

You can see the demo here.


You could do it like this:

var mydiv = document.getElementById("mydiv");
var content = "<script>alert(\"hi\");<\/script>";

mydiv.innerHTML = content;
var scripts = mydiv.getElementsByTagName("script");
for (var i = 0; i < scripts.length; i++) {

Krasimir Tsonev has a great solution that overcome all problems. His method doesn't need using eval, so no performance nor security problems exist. It allows you to set innerHTML string contains html with js and translate it immediately to an DOM element while also executes the js parts exist along the code. short ,simple, and works exactly as you want.

Enjoy his solution:

Important notes:

  1. You need to wrap the target element with div tag
  2. You need to wrap the src string with div tag.
  3. If you write the src string directly and it includes js parts, please take attention to write the closing script tags correctly (with \ before /) as this is a string.

Use $(parent).html(code) instead of parent.innerHTML = code.

The following also fixes scripts that use document.write and scripts loaded via src attribute. Unfortunately even this doesn't work with Google AdSense scripts.

var oldDocumentWrite = document.write;
var oldDocumentWriteln = document.writeln;
try {
    document.write = function(code) {
    document.writeln = function(code) {
        document.write(code + "<br/>");
} finally {
    $(window).load(function() {
        document.write = oldDocumentWrite
        document.writeln = oldDocumentWriteln



Try using template and document.importNode. Here is an example:

<!DOCTYPE html>
<meta charset="UTF-8">
<h1 id="hello_world">Sample</h1>
<script type="text/javascript">
 var div = document.createElement("div");
  var t = document.createElement('template');
  t.innerHTML =  "Check Console tab for javascript output: Hello world!!!<br/><script type='text/javascript' >console.log('Hello world!!!');<\/script>";
  for (var i=0; i < t.content.childNodes.length; i++){
    var node = document.importNode(t.content.childNodes[i], true);

Yes you can, but you have to do it outside of the DOM and the order has to be right.

var scr = '<scr'+'ipt>alert("foo")</scr'+'ipt>';
window.onload = function(){
    var n = document.createElement("div");
    n.innerHTML = scr;

...will alert 'foo'. This won't work:

document.getElementById("myDiv").innerHTML = scr;

And even this won't work, because the node is inserted first:

var scr = '<scr'+'ipt>alert("foo")</scr'+'ipt>';
window.onload = function(){
    var n = document.createElement("div");
    n.innerHTML = scr;  

My solution for this problem is to set a Mutation Observer to detect <script></script> nodes and then replace it with a new <script></script> node with the same src. For example:

let parentNode = /* node to observe */ void 0
let observer = new MutationObserver(mutations=>{>{
            if ( node.parentNode == parentNode ) {
                let scripts = node.getElementsByTagName('script')
                    let src = script.src
                    script = document.createElement('script')
                    script.src = src
                    return script
observer.observe(document.body, {childList: true, subtree: true});

You can also wrap your <script> like this and it will get executed:

<your target node>.innerHTML = '<iframe srcdoc="<script>alert(top.document.title);</script>"></iframe>';

Please note: The scope inside srcdoc refers to the iframe, so you have to use top like in the example above to access the parent document.


I had this problem with innerHTML, I had to append a Hotjar script to the "head" tag of my Reactjs application and it would have to execute right after appending.

One of the good solutions for dynamic Node import into the "head" tag is React-helment module.

Also, there is a useful solution for the proposed issue:

No script tags in innerHTML!

It turns out that HTML5 does not allow script tags to be dynamically added using the innerHTML property. So the following will not execute and there will be no alert saying Hello World!

element.innerHTML = "<script>alert('Hello World!')</script>";

This is documented in the HTML5 spec:

Note: script elements inserted using innerHTML do not execute when they are inserted.

But beware, this doesn't mean innerHTML is safe from cross-site scripting. It is possible to execute JavaScript via innerHTML without using tags as illustrated on MDN's innerHTML page.

Solution: Dynamically adding scripts

To dynamically add a script tag, you need to create a new script element and append it to the target element.

You can do this for external scripts:

var newScript = document.createElement("script");
newScript.src = "";

And inline scripts:

var newScript = document.createElement("script");
var inlineScript = document.createTextNode("alert('Hello World!');");

First note that mod(3^146,293)=292. For some reason, inputting mod(3^146,293) in Matlab returns 275. Inputting Math.pow(3,146) % 293 in JS returns 275. This same error occurs (as far as I can tell) ...

First note that mod(3^146,293)=292. For some reason, inputting mod(3^146,293) in Matlab returns 275. Inputting Math.pow(3,146) % 293 in JS returns 275. This same error occurs (as far as I can tell) ...

In JavaScript, I have $scope.dtOptionsCandidate = DTOptionsBuilder.newOptions() .withColReorder() .withLightColumnFilter({ 1: {"type": "text"}, 2: {"type": "text"}, 3: ...

In JavaScript, I have $scope.dtOptionsCandidate = DTOptionsBuilder.newOptions() .withColReorder() .withLightColumnFilter({ 1: {"type": "text"}, 2: {"type": "text"}, 3: ...

  1. angular datatable filtering
  2. angular datatable filter dropdown
  3. angular datatable filter column
  4. angular datatable filter not working
  5. angular datatable filter data
  6. angular datatable filter each column
  7. angular material data table filtering
  8. angular-6-datatable filter
  9. angular 6 datatable filter example
  10. angular datatable custom filter
  11. angular 2 datatable filter example
  12. angular datatables column filter example
  13. angular 7 datatable filter
  14. angular 4 datatable filter
  15. angular 4 datatable filter example
  16. angular ngx-datatable filter
  17. angular 2 datatable filter
  18. angular 5 datatable filter
  19. angular p-datatable filter
  20. angular datatable search filter

I am using Firebase to authenticate users in our app using GoogleAuthProvider. But I don't want a new user to sign in if they are not already an authenticated user. If the user exists then sign them ...

I am using Firebase to authenticate users in our app using GoogleAuthProvider. But I don't want a new user to sign in if they are not already an authenticated user. If the user exists then sign them ...

I am looping through elements using jQuery like this: $(".myelement").each(function() { $element = $(this).closest(".panel").attr("id"); console.log($element); }); This is working correctly and ...

I am looping through elements using jQuery like this: $(".myelement").each(function() { $element = $(this).closest(".panel").attr("id"); console.log($element); }); This is working correctly and ...

  1. create list from array
  2. create list from string python
  3. create list from dataframe
  4. create list from dictionary python
  5. create list from range python
  6. create list from text file python
  7. create list from column pandas
  8. create list from csv python
  9. create list from for loop python
  10. create list from 0 to n python
  11. create list from excel
  12. create list from template sharepoint
  13. create list from dictionary values python
  14. create list from string java
  15. create list from set
  16. create list from dictionary keys python
  17. create list from input python
  18. create list from excel column
  19. create list from column r
  20. create list from numpy array