Print the content of a Div | JavaScript/jQuery

Printing a whole web-page is an easy task because it is a feature that is provided by web-browsers . However, in some situations, you may need to provide a functionality to your users for printing only a segment ( Div content ) of a web-page rather than the whole web page.
var mywindow = window.open(); var content = document.getElementById(elem).innerHTML; mywindow.document.write(content); mywindow.print();
In the above code, when you click the button "Print a Div" , a JavaScript popup window is created and extracted the contents of the HTML div elements to store it in a JavaScript variable. Then the contents of the HTML div elements are written to the popup window and finally the window is printed using the JavaScript Window print() command.
run this source code Browser View

Print This Image...

JS print Div

Full Source | JavaScript

<!DOCTYPE html> <html lang="en"> <head> <title>Print a div content using JavaScript</title> </head> <body> <div id="printThisDiv"> <h2>Print This Image...</h2> <img src="javascript-print-div.png" alt="JS print Div" width="185" height="184"> </div> <input type="button" onclick="printDiv('printThisDiv')" value="Print a Div" /> </body> <script> function printDiv(elem) { var mywindow = window.open(); var content = document.getElementById(elem).innerHTML; var realContent = document.body.innerHTML; mywindow.document.write(content); mywindow.document.close(); // necessary for IE >= 10 mywindow.focus(); // necessary for IE >= 10*/ mywindow.print(); document.body.innerHTML = realContent; mywindow.close(); return true; } </script> </html>