Skip to content

Instantly share code, notes, and snippets.

@chibaye
Created May 12, 2019 13:43
Show Gist options
  • Save chibaye/672c8301bc0d36bce0d5b295362014dd to your computer and use it in GitHub Desktop.
Save chibaye/672c8301bc0d36bce0d5b295362014dd to your computer and use it in GitHub Desktop.
JS: Print content of div
<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>

JS: Print content of div

A method using JavaScript to only print the content of a specific div

A Pen by Martin on CodePen.

License.

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;
});
.hidden {
display:none;
}
body {
background: #edfffe;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment