title: Is it possible to "sandbox" arbitrary JavaScript to only operate on one <div> and not the whole document?
body: <p>what I am trying to do is to force some arbitrary JavaScript code to execute "inside" a DOM element, e.g. <code>&lt;div&gt;</code>. In other words, is it possible to make a piece of code "thinking" that <code>&lt;div&gt;</code> is the root of document hierarchy (or <code>&lt;body&gt;</code> of a document)?</p>
  
  <p><strong>Real life example:</strong></p>
  
  <p>Let's say we have a page that allows executing JavaScript code:</p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;Executor&lt;/title&gt;
    &lt;script type="text/javascript" src="jquery.js"&gt;&lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;div&gt;&lt;/div&gt;
    &lt;input/&gt;
    &lt;button onclick="$('div').html(eval($('input').val()))"&gt;
      Execute
    &lt;/button&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>The code has access to entire document and can modify it, e.g:</p>
  
  <pre><code>$("input").hide()
  </code></pre>
  
  <p>Will prevent me from writing any stupid code any more ;-)</p>
  
  <p>Is is possible to restrict the area of effect for some piece of JavaScript code? and how to do it if it is possible?</p>
  
  <p>Best regards.</p>
  
  <p><strong>Edit:</strong></p>
  
  <p>The code I want to execute might be everything. If Your solution is based on some kind of modification of the given code, please describe how to do it the right way.</p>
  
  <p><strong>Edit2:</strong></p>
  
  <p>First of all, I do not know why I get a down-vote.</p>
  
  <p>Secondly, the code I will execute is someone else's arbitrary code, not mine.</p>
  
  <p><strong>To make everything clear:</strong></p>
  
  <p>What I am really trying to do is to simulate a browser somehow. Get the content of some web page, and insert in into mine. This is relatively easy when we decided to turn off JavaScript and cut out all places where it might appear, but this is something I cannot do. For now I want to limit only the DOM modification (the malicious code). I will work on redirects and cookies later, when I have a base idea.</p>