title: How do I execute javascript only relative to that frame and not the whole window?
body: <p>I have the following iFrame:</p>
  
  <pre><code>&lt;div id="sandbox-inner"&gt;
      &lt;iframe sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts" frameborder="0" name="Output " id="output" src="JavaScript:''"&gt;&lt;/iframe&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>And when the user clicks to run their code, it injects the javascript successfully within this iframe. However, it actually runs it across the whole window, not just the iframe. So basically if I add a class "test" to an element outside the iframe, and one inside, and then inject the following inside the head of the iframe...</p>
  
  <pre><code>$(function() {
        $('.test').css({ background: "blue" });
  });
  </code></pre>
  
  <p>It effects my element outside the iframe too, which I really dont want. I need the iFrame to be a completely seperate environment. This is how I am currently injecting the javascript:</p>
  
  <pre><code>$('#runGuestCode').on("click", function () {
  
          var js = $('#js-input').val(),           
              iframe = $("#output"),
              iframeHead = iframe.contents().find("head").first(),
              frame = document.getElementById("output"),
              scriptTag = '&lt;script&gt;' + js + '&lt;\/script&gt;';
  
          $('#output').contents().find("head").append(scriptTag);
      });
  </code></pre>
  
  <p>Many thanks</p>
  
  <p>UPDATE #1</p>
  
  <p>The javascript is taken from textarea #js-input, which is whatever the user has typed. This is then appended to the head of the iframe, but currently runs relative to the parent document, not the iframe document. </p>