This tutorial will illustrate the procedure to print a particular part of a web page using JavaScript.
How to Print a Specific Part of a Web Page?
To print the specific part of the web page with high quality:
- Use the “getElementById()” method to get the reference of the content element.
- Then, utilize the “window.open” method, which opens the print window with the specified size.
- “window.document.write” writes the text in the window.
- “window.document.close” closes the document.
- “window.focus()” sets the focus on the print window’s content.
- Finally, use the “window.print()” for printing the content.
Example
In an HTML file, first, create a div in a web page with some content:
Create a print button outside the div and attach an “onclick” event with it that calls the function “print()” while it is clicked:
After executing the above-given code, the web page will look like as follows:
Now, in the JavaScript file, or the tag, add the given lines of code:
var printDiv = document.getElementById("divPrint");
var printWindow = window.open('', '', 'left=0, top=0, width=800, height=500, toolbar=0, scrollbars=0, status=0');
printWindow.document.write(printDiv.innerHTML);
printWindow.document.close();
printWindow.focus();
printWindow.print();
}
In the above code snippet:
- First, define the “print()” method that is invoked when the “onclick” event is triggered.
- Get the element (div) that you want to print by passing its assigned id to the “getElementById()” method.
- Call the “window.open()” method and pass the window size according to your requirement.
- Pass the reference of the div element to the “window.document.write()” method with the “innerHTML” property to write the content on the print window.
- Then, close the document using the “window.close()” method.
- Set focus on the print window using the “window.focus()” method.
- Finally, call the “print” method of the window object to print the specified content.
Output
That’s all about printing the specified part of the web page.
Conclusion
To print the specific part of the web page, use the “getElementById()” method to get the reference of the element of the content. Then, use the “window’s” methods, including “window.open”, “window.document.write”, “window.document.close”, “window.focus()”, and “window.print()”. In this tutorial, we illustrated the procedure for printing a particular part of a web page using JavaScript.