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
1 Answer 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.
javascript:btw if you don't usebreakor things like that).evalhere to get the exact functionality.