user5572578
user5572578

Reputation: 159

Is it possbile to take text (inner HTML) and make it into JavaScript code?

I want to design a website that is called something like "JavaScript Code Drills" where users get prompts of coding interview-like problems and can write solutions which get tested for validity. This is will all be done on the frontend. So I somehow need to go from something like

<script>
var f; 
</script>
<div class="prompt">
   <p>Write the body of a function whose one parameter is an array and returns the maximum element of the array (If the array is empty, return undefined).</p>
</div>
<div class="solution">
    function ( arr )
    {
       var max = arr.length > 0 ? arr[0] : undefined;
       for ( var i = 1; i < arr.length; ++i ) if ( arr[i] > max ) max = arr[i];
       return max;
    }
</div>

and from that, somehow getting the variable f to equal the contents of #solution as JS code. Is this type of transformation possible?

Upvotes: 1

Views: 48

Answers (1)

www139
www139

Reputation: 5237

Does this help? I will improve if it doesn't work for you :)

I changed the HTML for simplicity. Please see http://www.w3schools.com/jsref/jsref_eval.asp for more information about the eval() function.

window.addEventListener('load',function(){
  var f = document.getElementById('solution').innerHTML;
  eval(f);
});
<div class="prompt">
  <p>Write the body of a function whose one parameter is an array and returns the maximum element of the array (If the array is empty, return undefined).</p>
</div>
<div id="solution">
  alert('testing');
</div>

Upvotes: 1

Related Questions