DEV Community

Pablo Garcia
Pablo Garcia

Posted on

Print a single element from a webpage using JavaScript

I use this code snippet in the dev tools to print a small portion of a webpage. It copies every CSS stylesheet in the head of the page which helps render the printed content as close as possible to how it appears in the browser.

function printElement(element) {
    const newWin = window.open('', 'Print-Window');

    // Copy all stylesheets
    let stylesheets = '';
    for (var i = 0; i < document.styleSheets.length; i++) {
        if (document.styleSheets[i].href) {
            stylesheets += '<link rel="stylesheet" href="' + document.styleSheets[i].href + '" type="text/css">';
        }
    }

    newWin.document.open();
    newWin.document.write('<html><head>' + stylesheets + '</head><body>' + element.innerHTML + '</body></html>');
    newWin.document.close();
    setTimeout(function () {
        newWin.print();
        // newWin.close(); // close tab after printing
    }, 250); // Delay to ensure styles are applied
}

// Usage
// printElement(document.getElementById('myElementId'));
// printElement(document.querySelector('#myElementId'));
// 
// If you already have an element selected in the dev tools:
// printElement($0);
Enter fullscreen mode Exit fullscreen mode

How to use

  1. Open the dev tools
  2. Copy & paste the function above into the Console
  3. Select the div you want to print
  4. Then run printElement($0)

Screenshot showing steps to run this function in the dev tools in Chrome

Examples

As shown in the screenshot above, I use this often with ChatGPT responses when I want to print just one answer that might be too long to fit on a screenshot. This is actually helpful if you are creating GPTs, where you need to upload a PDF from one of the responses from GPT.

For example, this is how it looks originaly:
Screenshot of one answer of GPT showing a factorial

This is how it looks when running printElement($0); on that div:
Screenshot that shows a print dialog on a new tab after running pringElement when the div was selected in the dev tools

And this is what it looks if you close the print dialog:
Screenshot that shows the new tab after closing the dialog: it shows that the styles were copied as good as it can be

Conclusion

Although this simple function isn't 100% bullet proof, it helps printing certain parts of a website while attempting to keep the styles as best as it can.

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay