Print the content of a Div | JavaScript/jQuery

Printing an entire web page is a built-in feature provided by web browsers. Yet, there are scenarios where you might require users to print a specific segment, such as the content within a <div> , rather than the entire page. This targeted printing can be achieved through JavaScript, enabling more fine-grained control over what gets printed.

var mywindow = window.open(); var content = document.getElementById(elem).innerHTML; mywindow.document.write(content); mywindow.print();

In the above code, demonstrates a process where clicking the "Print a Div" button initiates the creation of a JavaScript popup window. This window is utilized to extract and store the contents of HTML <div> elements within a JavaScript variable. Subsequently, the content of these HTML elements is inscribed into the popup window, and the final step involves printing the window using the JavaScript window.print() command. This sequence of actions facilitates the selective printing of specific content from the webpage.

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>

Conclusion

Printing the content of a <div> using JavaScript involves extracting the content with innerHTML and creating a new window to display it. This approach enables users to initiate printing through the browser's print functionality.