How to print div content using javascript?

Today, We want to share with you print div in javascript.In this post we will show you To print the data content of div in js, added content of div in a js variable after that the print button is clicked, hear for Print the content of a div element using JavaScript we will give you demo and example for implement.In this post, we will learn about jQuery Print Dynamic Content using PHP MySQL with an example.

How to print div content using javascript/jQuery?

Example 1: index.html

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<body>
   <div id='writeNameOnPictureDownload'>
      <p>I am inside the div tag...</p>
   </div>
   <p>I am not inside the div tag...</p>
   <input type='button' id='getDataPage' value='Press Me To display the data'>
   <div id="pageDataDisplay"></div>
</body>
<script>
   $('#getDataPage').on('click', function () {
      showContent();
   })
   function showContent() {
      $(document).ready(function () {
         $("#pageDataDisplay").html($("#writeNameOnPictureDownload").html());
      });
   }
</script>
</html>

JS: Print content of div

HTML Code

<h2>JS: Print content of div</h2>

<div class="hidden">
  <div id="pageDataDisplay">
    <h3>This will be printed</h3>
  </div>
</div>

<div>
  <h3>This won't be printed</h3>
</div>

<button id="writeNameOnPictureDownload">Print</button>

CSS Code

.hidden {
  display:none;
}

body {
  background: #edfffe;
}

JS Code

document.getElementById("writeNameOnPictureDownload").addEventListener("click", function() {
     var printContents = document.getElementById('pageDataDisplay').innerHTML;
     var originalContents = document.body.innerHTML;
     document.body.innerHTML = printContents;
     window.print();
     document.body.innerHTML = originalContents;
});

I hope you get an idea about div content with background image javascript.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.