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

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

Comments

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!';")

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.