How to Print Specific Section of a Web page using javascript

In this post, I would like to show how to print a specific section of a web page. Many times we needed to print the section as per our requirements for example- if we have employee details and his/her salary details in the same page and we want only the print of salary details section then we can get this through javascript.
Here is I am defining two div section with unique ID. One is for employee details and other is for salary details. And the div ID passes from the click function of anchor tag through to the javascript function. And in the javascript function we can get html content through innerhtml property and can print it. Please find below the code.
printsection.html
<html> <head> <title>Print specific section example</title> <style> @media print { .noprint{ display: none !important; } } </style> </head> <body> <div id="employee_details" > <table align="center" cellspacing = "0" style="background-color:lightgrey;" width="80%" border="1"> <tr><td>Employee Details</td><td colspan="3" align="right"><a href="javascript:void(null);" onclick="print_section('employee_details')" class="noprint">Print</a></td></tr> <tr> <td>Name</td> <td><label>Mr. Ajay Trivedis</label></td> </tr> <tr> <td>Mobile: </td> <td><label>789321</label></td> </tr> <tr> <td>Adress: </td> <td><label>Mumbai</td> </tr> </table> </div> </br> <div id="payment_details" > <table align="center" cellspacing = "0" style="background-color:#d09d9d;" width="80%" border="1"> <tr><td>Salary Details</td><td colspan="4" align="right"><a href="javascript:void(null);" onclick="print_section('payment_details')" class="noprint">Print</a></td></tr> <tr> <td>Date: </td> <td><label>27/08/2018</label></td> </tr> <tr> <td>Gross: </td> <td><label>20,000/-</label></td> </tr> <tr> <td>Net Payout: </td> <td><label>18,000/-</td> </tr> </table> </div> <script type="text/javascript"> function print_section(section) { var printContents = document.getElementById(section).innerHTML; var originalContents = document.body.innerHTML; document.body.innerHTML = printContents; window.print(); document.body.innerHTML = originalContents; } </script> </body> </html>

Thank you for reading this post. we hope you like this Post, Please feel free to comment below, your suggestion and problems if you face – let us know. We’d love to help!