Explain Codes LogoExplain Codes Logo

Print the contents of a DIV

javascript
print
dynamic-content
cross-browser
Alex KataevbyAlex Kataev·Aug 5, 2024
TLDR

Let's get straight to the point. Want to print a DIV's content? Trigger a popup with that content, and run your browser's print function. Here's the quick, ready-to-deploy code:

function printDiv(divId) { var divContent = document.getElementById(divId).innerHTML; // Your DIV's sweet content var printWin = window.open('', '_blank', 'width=800,height=600'); // Hello popup printWin.document.write(`<html><head><title>Special delivery from Print DIV Contents, Inc.</title></head><body>${divContent}</body></html>`); printWin.document.close(); // Safety first. Always close what you've opened! printWin.addEventListener('load', function() { printWin.print(); // Print order up! printWin.close(); // And... cut! }, true); }

Get this printer rolling by calling printDiv('yourDivId'), where 'yourDivId' is the ID of your go-to DIV. The script will handle the rest — loading the content and hitting the print buttons for you.

Advanced problems? Advanced solutions!

The strange case of dynamic content

Is your DIV filled with forms or fancy JavaScript pieces? You'll need to approach it differently. Clone the DOM subtree, voilà! You preserve the interactivity before you hit print:

function printDivWithDynamicContent(divId) { const printWin = window.open('', '_blank', 'width=800,height=600'); const originalDiv = document.getElementById(divId); // Clone wars: Clone the original DIV, dynamic content and all const cloneDiv = originalDiv.cloneNode(true); printWin.document.body.appendChild(cloneDiv); printWin.document.close(); printWin.addEventListener('load', function() { printWin.print(); printWin.close(); }, true); }

Fashion matters: Styling for print

Looks matter. Sometimes, printing might not Instagram your beautiful CSS styles. Use @media print to shower your print with styles, or inline some styles when needed:

// Fashion police here, we'll add inline styles for you! function addInlinePrintStyles(divContent) { var inlineStyles = '<style>' + ' body { font-family: Arial, sans-serif; color: #333; }' + ' /* Insert your fabulous styles here. Vogue! */' + '</style>'; return inlineStyles + divContent; } // Call the fashion police before printing your DIV function printDiv(divId) { var divContent = document.getElementById(divId).innerHTML; divContent = addInlinePrintStyles(divContent); // Applying styles, runway ready! // ... the rest of the function is a familiar song }

Extra! Extra! Images and iframes

You've got images or iframes? Ensure they're all loaded and ready for their closeup before you print:

function printDivWithImages(divId) { // ... same ol', same ol' ... printWin.addEventListener('load', function() { // All images posing for the camera? var allImagesLoaded = Array.from(printWin.document.images).every((img) => img.complete); if (allImagesLoaded) { printWin.print(); printWin.close(); // And... it's a wrap! } else { // If no, alert the director or fill in your own twist in the plot } }, true); }

Browsers, always the divas!

Cross-browser compatibility

Test your printing function across different browsers. Different browser, different dance rules. Keep an eye out for fallbacks for the old folk.

Chrome-specific considerations

Chrome, the rockstar. Make sure you're not blocked by any popup-blocking features. Rockstars hate party poopers.

Printing forms, not just papers

Does your DIV host forms? Make sure those values make it to the print. Run through each form input, and trash "CTRL+C" with this bad boy:

// Copy-Paste is so yesterday! function copyFormValues(originalForm, clonedForm) { var originalInputs = originalForm.querySelectorAll('input, select, textarea'); var clonedInputs = clonedForm.querySelectorAll('input, select, textarea'); originalInputs.forEach(function(originalInput, index) { var clonedInput = clonedInputs[index]; clonedInput.value = originalInput.value; // Secret handover }); }