How to print the contents of a div with JavaScript?

Spread the love

Sometimes, we want to print the contents of a div with JavaScript.

In this article, we’ll look at how to print the contents of a div with JavaScript.

How to print the contents of a div with JavaScript?

To print the contents of a div with JavaScript, we can use the window’s print method.

For instance, we write

const printDiv = (elementId) => {
  const printElement = document.getElementById(elementId);
  const printWindow = window.open("", "PRINT");
  printWindow.document.write(document.documentElement.innerHTML);
  setTimeout(() => {
    printWindow.document.body.style.margin = "0 0";
    printWindow.document.body.innerHTML = printElement.outerHTML;
    printWindow.document.close();
    printWindow.focus();
    printWindow.print();
    printWindow.close();
  }, 1000);
};

to define the printDiv function.

In it, we select the element to print with getElementById.

Then we call window.open to open a new window.

Next, we populate the window’s content with the element’s contents with

printWindow.document.body.innerHTML = printElement.outerHTML;

Then we close and focus on the print document with

printWindow.document.close();
printWindow.focus();

Next, we print the window’s content with

printWindow.print();

Then we close the window with

printWindow.close();

Conclusion

To print the contents of a div with JavaScript, we can use the window’s print method.

Leave a Reply

Your email address will not be published. Required fields are marked *