This code enables you to print the content of a specific div using JavaScript without opening a new window. The printDiv
method copies the content of the div with the id “printableTable” into a hidden iframe and then triggers the print dialog. This functionality is helpful for easily printing specific content from a webpage without the need for a new window.
Moreover, this code is versatile and can be applied in various scenarios such as generating print-friendly reports, documentation, custom print views, and more.
How to Create Print Div Content Feature Using JavaScript
1. Create the HTML structure for our webpage. In this example, we’ll have a div element with some content that we 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>
2. Add the following CSS code to your stylesheet. This code will hide all elements by default when printing, except for the elements inside the “printableTable” <div>
.
- @media print {
- * {
- display: none;
- }
- #printableTable {
- display: block;
- }
- }
3. Finally, include the following JavaScript function in your HTML file or an external JavaScript file. This function copies the content of the “printableTable” <div>
to a hidden iframe and triggers the print dialog.
- 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();
- }
That’s all! hopefully, you have successfully created functionality to print div content using JavaScript without opening new window. If you have any questions or suggestions, feel free to comment below.
Similar Code Snippets:

I code and create web elements for amazing people around the world. I like work with new people. New people new Experiences.
I truly enjoy what I’m doing, which makes me more passionate about web development and coding. I am always ready to do challenging tasks whether it is about creating a custom CMS from scratch or customizing an existing system.