I'm attempting to get elements from a form so that the results can be styled and printed from an iframe. Here is the code I'm using:
const printButton = document.getElementById('print-quiz');
var clone = document.querySelector('.quiz_results').cloneNode( true );
printButton.addEventListener('click', event => {
this.event = event;
// New HTML page
const user = "<table><tr><td>" + document.querySelector('.quiz_results').appendChild(clone) + "</td></tr></table>";
const printHtml = `<html><head><meta charset="utf-8"><title>Printed Quiz</title></head><body>${user}</body></html>`;
// get the iframe
let iFrame = document.getElementById('print-quiz');
iFrame.contentDocument.body.innerHTML = printHtml;
iFrame.focus();
iFrame.contentWindow.print();
});
All is well except, document.querySelector('.quiz_results').appendChild(clone) returns [object HTMLDivElement]
How can I modify my code to duplicate the div class (.quiz_results) and its inner contents into the html results iframe? I've been at this for a while and appreciate your assistance.
Yes you can clone an element to another document. Although just for printing you could have used the outerHTML
(or innerHTML
) property.
Your mistake was adding an HTMLElement
to string
. You should either append element to element, or concatenate string to another.
A working copy: https://jsfiddle.net/w04h9psd/
const printButton = document.getElementById('print-quiz');
var clone = document.querySelector('.quiz_results').cloneNode(true);
printButton.addEventListener('click', event => {
this.event = event;
// New HTML page
const user = "<table><tr><td id='user-container'></td></tr></table>";
const printHtml = `<html><head><meta charset="utf-8"><title>Printed Quiz</title></head><body>${user}</body></html>`;
// get the iframe
let iFrame = document.getElementById('print-iframe');
iFrame.contentDocument.body.innerHTML = printHtml;
iFrame.contentDocument.getElementById("user-container").append(clone)
iFrame.focus();
iFrame.contentWindow.print();
});
<button id="print-quiz">print quiz</button>
<div class="quiz_results">quiz_results: 100, 30, 60</div>
<iframe id="print-iframe"></iframe>