Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (7k points)

I want to print some HTML content when the user clicks on a button. Once the user clicks on the button, the print dialog of the browser will open, but it will not print the webpage. Instead, it will print some other HTML content that is not displayed on the page. Can somebody help me with this?

1 Answer

0 votes
by (13.1k points)

You can place printable part inside a div with an id like this:

<div id="printableArea">

      <h1>Print me</h1>

</div>

<input type="button" onclick="printDiv('printableArea')" value="print a div!" />

Place this in your script tag:

function printDiv(divName) {

     var printContents = document.getElementById(divName).innerHTML;

     var originalContents = document.body.innerHTML;

     document.body.innerHTML = printContents;

     window.print();

     document.body.innerHTML = originalContents;

}

Want to be a full stack developer? Check out the full stack developer course from Intellipaat

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...