title: Add JavaScript and HTML to IFRAME, and print IFRAME to printer
body: <p>There are multiple posts dealing with part of these topics, but none that puts them together.</p>
  
  <p>On a given page, I wish to create a new IFRAME, add some JavaScript to it which will print the page to a printer, and add some HTML to it which will be printed.</p>
  
  <p>Below is my attempt with a live demo at <a href="http://jsbin.com/UDUCADI/2/" rel="nofollow">http://jsbin.com/UDUCADI/2/</a>.  It prints, but prints the parent page and not the IFRAME.</p>
  
  <p>How do I just print the IFRAME?</p>
  
  <pre><code>&lt;!doctype html&gt;
  &lt;html lang="en"&gt;
      &lt;head&gt;
          &lt;meta charset="utf-8" /&gt;
          &lt;title&gt;Print IFRAME&lt;/title&gt;
          &lt;script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"&gt;&lt;/script&gt; 
          &lt;script type="text/javascript"&gt;
              $(function () {
                  $('#printIt').click(function(){
                      var iframe   = $('&lt;iframe&gt;');
                      var script   = document.createElement("script");
                      script.type  = "text/javascript";
                      script.text  = "window.print()";
                      iframe[0].appendChild(script);
                      iframe.appendTo('body');
                      var iframeDocument=$(iframe[0].contentWindow.document);
                      iframeDocument.find('body').html($('#stuffToPrint').html());
                  })
              });
          &lt;/script&gt;
      &lt;/head&gt;
      &lt;body&gt;
          &lt;button id="printIt"&gt;Print&lt;/button&gt;
          &lt;div id="stuffToPrint"&gt;
              &lt;p&gt;Print this text!&lt;/p&gt;
              &lt;img alt="And print this image" src="dropdown_arrow_blue.gif"&gt;
          &lt;/div&gt;
          &lt;div&gt;Don't print this!&lt;/div&gt;
      &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>