Ben G
Ben G

Reputation: 26761

Dynamically writing and evaluating a <script>

I want to dynamically write (and have evaluated) a script I write to a tag. Why won't this code work?

<html>
<head>

<script id="cojs">

</script>

<script type="text/javascript">
document.getElementById('cojs').innerHTML = 'alert("hey");';
</script>
</head>
<body>
</body>
</html>

Upvotes: 3

Views: 485

Answers (2)

kennebec
kennebec

Reputation: 104760

If you want a script to be interpreted you need to add it to the document. Some browsers don't use innerHTML for scripts, but all will set a script's text property.

<!doctype html>
<html lang= "en">
<head>
<meta charset= "utf-8">
<title> title</title>

<script>
    window.onload=function(){
        var head=document.getElementsByTagName('head')[0],
        who= document.createElement('script');
        who.text= 'alert("hey");';
        head.appendChild(who);
    }
</script>

</head>
<body>
</body>
</html>

Upvotes: 0

Konstantin Weitz
Konstantin Weitz

Reputation: 6422

Well script tags are evaluated when they are parsed. So since the section above is not parsed anymore after you alter it, it doesn't work.

If your usecase allows it try the eval function:

<html>
<head>
    <script type="text/javascript">
    eval('alert("hey");');
    </script>
</head>
<body>
</body>
</html>

Upvotes: 1

Related Questions