0

I have a div with some example code in it. I'd like to execute this code after pressing a button. Here's what I've tried:

HTML

<button onclick="javascript:playcode()"> </button>

JS

function playcode () {
     var execcode= "";
     for (i=1; i<=countCodeLine (); i++)
         execcode += document.getElementById("line"+i).innerText;

     var div= document.getElementById ("mydiv");
     var scr= document.createElement ('script', "");
     div.innerHTML= "play() {"+execcode+"}";
     div.appendChild(scr);
     play();
}

but it doesn't work. How can i do this?

UPDATE: here the errors from the console:

(line 9: pre.appendChild(scr)) Uncaught SyntaxError: Unexpected token { 
(line 10: play()) Uncaught TypeError: object is not a function 
10
  • 3
    Do you get any errors in your console? Commented Jul 11, 2013 at 9:45
  • 2
    what does not work? Do you get any errors? (You don't need the named jump label javascript: btw if you don't use break or things like that). Commented Jul 11, 2013 at 9:46
  • There's no reason this doesn't work, except if the onclick attribute was changed or the javascript not loaded. Commented Jul 11, 2013 at 9:47
  • 2
    Include all HTML code ... Commented Jul 11, 2013 at 9:47
  • 1
    it looks like you could just use an eval here to get the exact functionality. Commented Jul 11, 2013 at 9:48

1 Answer 1

1

If you are indeed getting the right HTML into execcode, you can use

eval(execcode);

You can check this by just doing a simple console.log(execcode) or alert(execcode) to verify that it's loaded correctly.

However, I can guarantee you that this is almost certainly a very, very bad idea. it'd be trivial for someone to just edit your DOM and insert whatever malicious javascript they want.

Sign up to request clarification or add additional context in comments.

1 Comment

you're welcome, but remember that you probably shouldn't do this in a production environment.

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.