Home / Programs / Printing a Page or Specific Element Data using JavaScript - window.print() method
🚀 Programming Example

Printing a Page or Specific Element Data using JavaScript - window.print() method

👁 241 Views
💻 Practical Program
📘 Step Learning

Printing a Page or Specific Element Data using JavaScript

📌 Information & Algorithm

In this section you will learn how to print particular element from a webpage. Here we have written one function myPrintfunction to print a paragraph.

💻 Program Code

 
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Functions to print Specific Element With Id - atnyla.com</h2>

<p>I Don't want to print this text.</p> 

<p id="textAreaToPrint">
This is the text I want to print.
</p>


<button type="button"  onclick="myPrintfunction()" class="btn btn-sm btn-outline-primary m-1"> Print </button> 


<script>
   function myPrintfunction(){
        var backup = document.body.innerHTML;
        var divcontent = document.getElementById("textAreaToPrint").textContent;
        document.body.innerHTML =  divcontent; 
        window.print();
        document.body.innerHTML = backup;
    }
</script> 
                                           

</body>
</html>
 
                        

🖥 Program Output

 <h3>Live Preview </h3>
<div class="shadow">
<img src="/library/images-tutorials/html-browser.png" class="img-thumbnail">
<div class="ratio ratio-16x9">
    <iframe class="embed-responsive-item" src="/library/javascript/functions/print-function.html"></iframe>
  </div>
</div> </div>
<hr> 
                            
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.