Printing specific sections of a webpage is a common requirement. This tutorial provides a straightforward method to print div content using Javascript without opening a new window, offering a seamless user experience. This is especially useful when you only want to print a specific part of a webpage, like a table or a chart, without the surrounding content.
Adding Header Assets
Add essential styles to your HTML document by including the following assets in the <head> tag.
<link rel='stylesheet' href='https://cdn.mutualofomaha.com/css/corporate/3.6.1/style.css'>
Creating the HTML Structure
Define the structure of your webpage, including the button to trigger the print function and the div containing the content you want to print.
<div>
<h1><b><center>This is a test page for printing</center></b><hr color=#00cc00 width=95%></h1>
<button class="Button Button--outline" onclick="printDiv()">Print</button>
<p> content content content </p>
<div id="printableTable">
<table>
<thead>
<tr>
<td>Thing</td>
<td>Chairs</td>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>blue</td>
</tr>
<tr>
<td>2</td>
<td>green</td>
</tr>
</tbody>
</table>
</div>
<p> content content content </p>
<p> content content content </p>
<iframe name="print_frame" width="0" height="0" frameborder="0" src="about:blank"></iframe>
</div>
<script src="./script.js"></script>
Applying CSS Styles
Use CSS to control how the content appears when printed. This example hides everything except the “printableTable” div when printing.
@media print {
* {
display: none;
}
#printableTable {
display: block;
}
}
Implementing the JavaScript Function
Implement the `printDiv()` function that will handle the printing process without opening a new window.
function printDiv() {
window.frames["print_frame"].document.body.innerHTML = document.getElementById("printableTable").innerHTML;
window.frames["print_frame"].window.focus();
window.frames["print_frame"].window.print();
}
Conclusion: You have now successfully implemented a method to print div content using Javascript without opening a new window. This technique enhances user experience and provides control over the printed output.







