0

I have a variable (string) in Javascript, in which you for example have this text:

"document.getElementById('tekst').innerHTML = 'Probeer opnieuw!';"

I got this variable using Ajax and PHP, but that is not where my (possibly very easy) question is about.

Say I want to use this code as code itself, not as a string, so instead of this being a string I would like the code inside of it to be executed.

How can I possibly do this?

Thanks in advance

R. Baauw
  • 51
  • 9

3 Answers3

3

Don't do this. It's a security nightmare.

If you really must do this, use eval() as in:

eval("document.getElementById('tekst').innerHTML = 'Probeer opnieuw!';");

Considering your example and explanation, I suspect that you are retrieving a url whose contents consist entirely of javascript. The problem you've run across is that the method you are using to retrieve that url gives you a string containing that javascript. I believe that it's intended for you to instead use a <script> element to load that code. To do so dynamically:

var script = document.createElement("script");
script.src = "url/to/your/javascript";
document.getElementByTagName('body')[0].appendChild(script);
Community
  • 1
  • 1
Ouroborus
  • 16,237
  • 4
  • 39
  • 62
1

You can use the eval() method. But don't do it if you don't have to. And if you do have to, make sure you know what you're doing.

eval("document.getElementById('tekst').innerHTML = 'Probeer opnieuw!';")
jessegavin
  • 74,067
  • 28
  • 136
  • 164
0

Here is an alternative to using eval() :

var stringContainingJavascript = "document.getElementById('tekst').innerHTML = 'Probeer opnieuw!';"

var body = document.getElementsByTagName('body')[0];

var paragraph = document.createElement('p');
paragraph.id = 'tekst';
body.appendChild(paragraph);

var script = document.createElement('script');
var scriptText = document.createTextNode(stringContainingJavascript);
script.appendChild(scriptText);
body.appendChild(script);

The script above creates a <p> element and gives it id="tekst", before appending the <p> to the <body> of the document.

The same script then creates a <script> element and appends the string to it, before appending the <script> to the <body> of the document.

Rounin
  • 27,134
  • 9
  • 83
  • 108