JavaScript Printing an Element Tutorial

In this tutorial, you will learn a simple way to print the specific element in your web applications page using JavaScript and jQuery. This technique is useful for your future project for printing reports that have already a display. With this, it helps you to prevent redundant coding just for creating a page for printing. Using this printing technique developer can also modify or customize the element before printing and without changing the original display.

Library Needed:

Method Use:

  • JS clone()
  • JS
  • JS setTimeout()
  • DOM Manipulation

Printing Code

Below is the example js script for printing the specific element on the window page. The script also includes all the styles and script loaded on the page to maintaint the design of the element to print.

  1. function print_el(){
  2. //HTML head tag that contains the loaded stylesheets and scritps
  3. var header = $('head').clone()
  4. //Cloning the Element to Print
  5. var el = $('#printout').clone()
  7. //Opening a new window
  8. var nw ='', '_blank', "width=" + ($(window).width() * .8) + ", left=" + ($(window).width() * .1) + ",height=" + ($(window).height() * .8) + ", top=" + ($(window).height() * .1))
  10. //Manipulating the New Window head tag
  11. nw.document.querySelector('head').innerHTML = header.html()
  12. //Manipulating the New Window content
  13. nw.document.querySelector('body').innerHTML = el[0].outerHTML
  14. nw.document.close()
  15. setTimeout(() => {
  16. //Printing the New Window
  17. nw.print()
  18. setTimeout(() => {
  19. nw.close()
  20. }, 300)
  21. }, 300)
  22. }

I will be providing below a simple HTML and JavaScript Source Code file for a simple web application that contains a feature that meets our goal for this tutorial. The source code only prints the specific element but maintains the element design.

Main Interface

The following script is the HTML file naming index.html. This file contains the HTML Scripts of the elements that are shown when browsing the page.

  1. <!DOCTYPE html>
  2. <html lang="en">
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>JS Custom Print</title>
  8. <!-- Styles -->
  9. <link rel="stylesheet" href="" integrity="sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g==" crossorigin="anonymous" referrerpolicy="no-referrer"
  10. />
  11. <link rel="stylesheet" href="[email protected]/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
  12. <!--end of Styles -->
  14. <!-- Scritps -->
  15. <script src="" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  16. <script src="[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
  17. <script src="" integrity="sha512-6PM0qYu5KExuNcKt5bURAoT6KCThUmHRewN3zUFNaoI6Di7XJPTMoT6K0nsagZKk2OB4L7E3q1uQKHNHd4stIQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  18. <script src="./script.js"></script>
  19. <!-- end of Scritps -->
  20. </head>
  22. <body class="bg-gradient-dark">
  23. <div class="content py-4">
  24. <div class="container">
  25. <div class="card rounded-0">
  26. <div class="card-header">
  27. <div class="d-flex w-100 align-items-center">
  28. <div class="col-auto flex-shrink-1 flex-grow-1">
  29. <div class="card-title"><b>Printing Page Element using JavaScrip</b></div>
  30. </div>
  31. <div class="col-auto">
  32. <button class="btn btn-success bg-gradient bg-success btn-sm rounded-0" type="button" id="print"><i class="fa fa-print"></i> Print Data</button>
  33. </div>
  34. </div>
  35. </div>
  36. <div class="card-body">
  37. <div class="container-fluid">
  38. <h5 class="fw-bolder">Data to Print:</h5>
  39. <div class="border rouded-0 border-dark p-2">
  40. <div id="printout">
  41. <div class="lh-1">
  42. <h1 class="text-center">Lorem Ipsum</h1>
  43. <h4 class="text-center mb-0">"Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit..."</h4>
  44. <h5 class="text-center fw-lighter mb-0">"There is no one who loves pain itself, who seeks after it and wants to have it, simply because it is pain..."</h5>
  45. </div>
  46. <hr>
  47. <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ac nisl nibh. Pellentesque sit amet orci lacinia, facilisis tortor in, ultrices enim. Maecenas elementum metus vitae lacus sodales viverra. Cras in ultrices orci,
  48. vel sollicitudin arcu. Aliquam erat volutpat. Praesent in nisi magna. In vel urna et turpis lobortis hendrerit in sed est. Aliquam eu enim felis. Vivamus eget accumsan ante. Pellentesque ut laoreet magna. Maecenas quis
  49. magna ac est finibus pharetra. Curabitur accumsan faucibus nunc, blandit congue tellus consectetur vitae. Proin auctor risus vel orci ornare, sit amet vestibulum nunc scelerisque. Suspendisse consectetur mi sit amet
  50. nisl sodales, in faucibus mi placerat. In maximus efficitur metus quis venenatis.</p>
  52. <p>Duis placerat id dui in vestibulum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Suspendisse sagittis, sapien sit amet congue blandit, leo nunc convallis mauris, ac lacinia nunc
  53. sem quis nulla. Nullam viverra, dui eu dapibus pellentesque, dolor diam luctus risus, a posuere diam nisi ac ligula. Sed at augue ut mauris lacinia pellentesque non sit amet ipsum. Donec sollicitudin faucibus facilisis.
  54. Sed viverra imperdiet arcu eget lacinia. Pellentesque ultricies rhoncus quam non feugiat. Etiam commodo lorem ac risus aliquam aliquam. Pellentesque eget nibh a nunc dapibus consectetur. Aliquam sapien turpis, molestie
  55. vel nunc vitae, placerat sollicitudin enim. Vivamus et tellus rhoncus diam rhoncus tristique et et dui. Nunc mattis, purus et mollis luctus, urna massa placerat mi, vel facilisis magna ligula ut felis. Orci varius natoque
  56. penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p>
  58. <h3><b>Table</b></h3>
  59. <hr>
  60. <table class="table table-stripped table-bordered">
  61. <tr class="bg-gradient bg-danger bg-opacity-25">
  62. <th class="py-1 text-center">#</th>
  63. <th class="py-1 text-center">Name</th>
  64. <th class="py-1 text-center">Contact</th>
  65. <th class="py-1 text-center">Address</th>
  66. </tr>
  67. </thead>
  68. <tr>
  69. <th class="py-1 text-center">1</th>
  70. <th class="py-1">Mark Cooper</th>
  71. <th class="py-1">09123456789</th>
  72. <th class="py-1">Sample Address #101</th>
  73. </tr>
  74. <tr>
  75. <th class="py-1 text-center">2</th>
  76. <th class="py-1">Samantha Jane Miller</th>
  77. <th class="py-1">09123654789</th>
  78. <th class="py-1">Sample Address #102</th>
  79. </tr>
  80. <tr>
  81. <th class="py-1 text-center">3</th>
  82. <th class="py-1">John Doe</th>
  83. <th class="py-1">09456789123</th>
  84. <th class="py-1">Sample Address #102</th>
  85. </tr>
  86. </tbody>
  87. </table>
  88. </div>
  89. </div>
  90. </div>
  91. </div>
  92. </div>
  93. </div>
  94. </div>
  95. </body>
  96. </html>

Page Display Snapshot

HTML Simple Website

Main Script

The following script is a JavaScript naming script.js. This file is included and loaded in the index.html file. It contains the JavaScript codes for printing the element file.

  1. $(function() {
  2. $('#print').click(function() {
  3. var header = $('head').clone()
  4. var el = $('#printout').clone()
  6. var nw ='', '_blank', "width=" + ($(window).width() * .8) + ", left=" + ($(window).width() * .1) + ",height=" + ($(window).height() * .8) + ", top=" + ($(window).height() * .1))
  7. nw.document.querySelector('head').innerHTML = header.html()
  8. nw.document.querySelector('body').innerHTML = el[0].outerHTML
  9. nw.document.close()
  10. setTimeout(() => {
  11. nw.print()
  12. setTimeout(() => {
  13. nw.close()
  14. }, 300)
  15. }, 300)
  16. })
  17. })

Print View Snapshot

HTML Simple Website

That's it! You can now test the source code on your end by browsing the index.html file in your preferred browser such as Chrome Browser. If you have encountered an error on your end, please review the changes you made to the scripts and differentiate them from the source code I provided above. You can also download the zip file of the source code I created for this tutorial. The download button is located below this article.


That's the end of this tutorial! I hope this JavaScript Tutorial for Printing the HTML Element will help you with what you are looking for and you'll find this tutorial useful for your future web application projects. Explore more on this website for more Tutorials and Free Source Codes..

Enjoy Coding:)

Add new comment

This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
2 + 3 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.