A method using JavaScript to only print the content of a specific div
Created
May 12, 2019 13:43
-
-
Save chibaye/672c8301bc0d36bce0d5b295362014dd to your computer and use it in GitHub Desktop.
JS: Print content of div
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<h2>JS: Print content of div</h2> | |
<div class="hidden"> | |
<div id="printDiv"> | |
<h3>This will be printed</h3> | |
</div> | |
</div> | |
<div> | |
<h3>This won't be printed</h3> | |
</div> | |
<button id="doPrint">Print</button> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
document.getElementById("doPrint").addEventListener("click", function() { | |
var printContents = document.getElementById('printDiv').innerHTML; | |
var originalContents = document.body.innerHTML; | |
document.body.innerHTML = printContents; | |
window.print(); | |
document.body.innerHTML = originalContents; | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.hidden { | |
display:none; | |
} | |
body { | |
background: #edfffe; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment