-1

For example:

<html>
    <div id="media">123</div>
    <a href="javascript:void(0)" onClick="return fun()">Click</a>
    <script type="text/javascript">
        function fun() {
            document.getElementById("media").innerHTML = '<script type="text/javascript">alert("working");<\/script>';
        }
    </script>
</html>

After you click the alert does not show.

alert("working"); is just an example. I want it to finish one job other javascript . I have a job to be processed through ajax should have used innerHTML

user2171180
  • 19
  • 1
  • 5
  • Possible dupplicate of http://stackoverflow.com/questions/1068517/why-cant-i-add-a-string-containing-a-script-tag-to-innerhtml-in-ie. – antoyo Mar 14 '13 at 18:56

3 Answers3

6

The HTML spec specifies that script tags inserted using innerHTML should not be executed. This is a security consideration.

There are still ways to do this if you are determined, such as adding it to img handlers or creating a script element, inserting it into the DOM and changing its text property. I will not elaborate on these, since doing this is generally considered somewhat sketchy. If you are not trying to inject script, you should include the script element in the page source.

Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139
1
<script type="text/javascript">

function fun() {
    alert("working");
}
</script>

<div id="media">123</div> <a href="javascript:void(0)" onClick="fun();">Click</a>
David L
  • 32,885
  • 8
  • 62
  • 93
  • alert("working"); is just example . I want it to finish one job other javascript – user2171180 Mar 14 '13 at 19:14
  • @user2171180 Well just type your javascript code inside the fun() function, no need to insert it with innerHTML. Why is that needed? – user2019515 Mar 14 '13 at 19:15
  • @user2171180. Exactly. Run your javascript FROM the fun function. You should never EVER insert it into innterHTML. My answer still solves your issue – David L Mar 14 '13 at 20:07
  • David L @user2019515 I have a job to be processed through ajax should have used innerHTML – user2171180 Mar 15 '13 at 04:58
  • @user2171180 First do the ajax job, then display the output with innerHTML in the media div, only display the output, not the javascript. – user2019515 Mar 15 '13 at 18:16
0

Your JS function should be like this.

function fun() {
  alert("working");
}
Mathieu G
  • 405
  • 5
  • 18