How to print a div on button click using javascript
By Ved Prakash N |
Aug 11, 2023 |
Javascript
Print the content of a div element using JavaScript
Hi guys, in this post, you will be learning about how to "print" the div tag content from html page using javascript / jquery. so guys lets get started:
Step 1: Create a HTML page named "index.html" with some content in it as follows:
<div id="myBillingArea">
<table style="width:100%;" cellpadding="5">
<thead>
<tr>
<th align="start" style="border-bottom: 1px solid #ccc;" width="5%">ID</th>
<th align="start" style="border-bottom: 1px solid #ccc;">Product Name</th>
<th align="start" style="border-bottom: 1px solid #ccc;" width="10%">Price</th>
<th align="start" style="border-bottom: 1px solid #ccc;" width="10%">Quantity</th>
<th align="start" style="border-bottom: 1px solid #ccc;" width="15%">Total Price</th>
</tr>
</thead>
<tbody>
<tr>
<td style="border-bottom: 1px solid #ccc;">1</td>
<td style="border-bottom: 1px solid #ccc;">Lenovo idea gaming</td>
<td style="border-bottom: 1px solid #ccc;">53,000</td>
<td style="border-bottom: 1px solid #ccc;">1</td>
<td style="border-bottom: 1px solid #ccc;">53,000 </td>
</tr>
<tr>
<td style="border-bottom: 1px solid #ccc;">2</td>
<td style="border-bottom: 1px solid #ccc;">Mi Note 8 Pro</td>
<td style="border-bottom: 1px solid #ccc;">16,000</td>
<td style="border-bottom: 1px solid #ccc;">1</td>
<td style="border-bottom: 1px solid #ccc;">16,000 </td>
</tr>
<tr>
<td colspan="4" align="end" style="font-weight: bold;">Grand Total: </td>
<td colspan="1" style="font-weight: bold;">69,000</td>
</tr>
</tbody>
</table>
</div>
Step 2: Add the below button in your index.html file
<button type="button" onclick="printDiv()">Print</button>
Step 3: Add the below script to Print the HTML div content
function printDiv() {
var divContents = document.getElementById("myBillingArea").innerHTML;
var a = window.open('', '');
a.document.write('<html><title>Funda of Web IT</title>');
a.document.write('<body style="font-family: fangsong;">');
a.document.write(divContents);
a.document.write('</body></html>');
a.document.close();
a.print();
}
That's it,
Thanks for reading.