Copy the contents of the div into a new iframe
P粉042455250
2023-08-17 17:03:59
<p>Ultimately I'm trying a technique that prints a specific <code>div</code> but I'm stuck on this part of the question. </p>
<p>I have some code that should be copied from a <code>div</code> to a new <code>iframe</code>: </p>
<pre class="brush:js;toolbar:false;">var iframe = document.createElement('iframe');
var div = document.querySelector('div#sidebar');
var content = div.innerHTML;
iframe.srcdoc = `<!DOCTYPE html><html><head></head><body>${content}</body></html>`;
document.body.append(iframe);
iframe.contentWindow.print();
</pre>
<p>I tried this in the developer tools on the SO page (I could try using <code>div#sidebar</code>). </p>
<p>I noticed that I need to add <code>iframe</code> to the document for this to work. Otherwise, the <code>.contentWindow</code> property is <code>null</code>. </p>
The <p>code seems to work to some extent, but the <code>iframe</code> is empty, or appears to be empty. The final printout is blank. </p>
<p>Any tips in creating a new <code>iframe</code> with copied content? </p>
Okay, I have an answer. I should know better as I just finished teaching a similar topic.
The code is valid, but it runs too early. I need to wait for the document to finish loading.
This is a working version: