Wednesday, January 25, 2017

How to execute JavaScipt code inserted as innerHTML/text in DOM

If you tried to load scripts into a page using innerHTML on HTML element like div it will not be executed.

The alert statement in below code will not be executed since it is set as inner HTML.

document.getElementById('divTemp').innerHTML = "<scr" + "ipt>alert('hi')</scr" + "ipt>";

You can use eval() but there is an easier and better way to do this. That is to load the script element into DOM.

Here is an example -

        var script1 = document.createElement("script");
        script1.innerHTML = "alert('hi');";
        document.body.appendChild(script1);

In this way you can execute javascript statements set as innerHTML or text. This will help you to execute scripts that are loaded asynchronously using APIs.

Live example in codepen- 

No comments: