jamex
jamex

Reputation: 621

how to assign a block of html code to a javascript variable (to invoke a javascript call)

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

Upvotes: 2

Views: 823

Answers (2)

Kent Fredric
Kent Fredric

Reputation: 57354

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™.

Upvotes: 2

strager
strager

Reputation: 90012

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.

Upvotes: 2

Related Questions