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
You cannot inject a
<script>element using.innerHTMLand expect it to evaluate. You must use eitherevalordocument.writeor inject the<script>into the DOM the “normal” way. With dynamic scripts,evalis recommended.Remember that
evalevaluates pure JavaScript and does not use the HTML interpreter. (Contrast this with PHP’s default behaviour, whereevalis like inserting?>$string<?phpinto 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 thedocument.writemethod, which has many problems and should be avoided where size isn’t an extreme issue).Here’s an example of using
eval: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.