views:

60

answers:

2

Hi,

I want to assign a block of html code to a js variable

the html code is

<script>alert('test');</script>

I want to do this

var script = "<script>alert('test');</script>";

document.getElementById('test').innerHTML = script;

but it does not work

if I substitute the tag (or any other tag) for the tag, then it works.

var script = "<span>alert('test');</span>";

I tried

var script = "<script>alert('test');</script>";
eval(script);

and

eval ("<span>alert('test');</span>");

but they both have syntax errors.

It probably has to do with have script tags inside of script tags

<script> <script> </script> </script>

Is there a way to get around this?

TIA

+2  A: 

You cannot inject a <script> element using .innerHTML and expect it to evaluate. You must use either eval or document.write or inject the <script> into the DOM the "normal" way. With dynamic scripts, eval is recommended.

Remember that eval evaluates pure JavaScript and does not use the HTML interpreter. (Contrast this with PHP's default behaviour, where eval is like inserting ?>$string<?php into the document.)

Also remember that a script terminates when it approaches </script>. It's strange to be inserting </script> into JavaScript anyway (unless you're using the document.write method, which has many problems and should be avoided where size isn't an extreme issue).

Here's an example of using eval:

var script = 'alert("test");';
eval(script);

If you want to inject a script into the DOM with other elements, you need to extract the <script> element after injecting and execute the (internal or external) script. Frameworks like jQuery and Prototype do this automatically, which is one of the many reasons why they are recommended over vanilla JavaScript.

strager
Thank you strager. This appears to work for my purpose.
jamex
+2  A: 

The way to do this with pure DOM methods I believe is as follows.

var script = document.createElement("script");
script.type = "text/javascript";
script.innerHTML = "alert('foo!')"; 
document.body.appendChild( script );

Works for me™.

Kent Fredric
Doesn't work in IE. =[ http://jsbin.com/ivigi4
strager
Thanks Kent, I will test it out.
jamex
I guess that's because IE has a broken DOM?
Kent Fredric