Print Div Content Using JavaScript

Print the content of div is a task we commonly need in projects.

In this article, we are going to see how to print content of HTML div using JavaScript.

To print a div content, we create a function and call it on onclick event of print button.

In the function, we store the div content data in JavaScript variable. Then we create a
popup window and then write html div content in it.

At the end, we print the window using the javascript print window command.

That’s all.

Table of Contents

HTML

<h1> Do not print this heading </h1>
<p> Do not print this paragraph </p>

<div id='printArea'>
  Print this only 
</div>

<button onclick="printDiv('printArea')">Print</button>

JavaScript

<script>
function printDiv(divID) {
 var divElem = document.getElementById(divID).innerHTML;
 var printWindow = window.open('', '', 'height=210,width=350');
 printWindow.document.write('<html><head><title></title></head>');
 printWindow.document.write('<body>');
 printWindow.document.write(divElem);
 printWindow.document.write('</body>');
 printWindow.document.write ('</html>');
 printWindow.document.close();
 printWindow.print();
}
</script>

Conclusion

In this tutorial, you have learned how to print div content using JavaScript.

Leave a Comment