Skip to content

Instantly share code, notes, and snippets.

@andrewlimaza
Created December 19, 2016 11:31
Show Gist options
  • Star 43 You must be signed in to star a gist
  • Fork 15 You must be signed in to fork a gist
  • Save andrewlimaza/490a69417d9fe2df3f668195a7661605 to your computer and use it in GitHub Desktop.
Save andrewlimaza/490a69417d9fe2df3f668195a7661605 to your computer and use it in GitHub Desktop.
Print certain div / elements using window.print()
<script>
function printDiv(divName){
var printContents = document.getElementById(divName).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
</script>
<h1> do not print this </h1>
<div id='printMe'>
Print this only
</div>
<button onclick="printDiv('printMe')">Print only the above div</button>
@crushman1
Copy link

@Vanilagy not sure how you got this one to work but i get an error Type 'HTMLCollection' must have a '[Symbol.iterator]()' method that returns an iterator at [...body.children] and when i run the function i get element.cloneNode is not a function in the inspector console

@azeenGAN
Copy link

azeenGAN commented Mar 2, 2024

just add return false after window.print() at the end of print function and your DOM will work properly as before

All other js stopped working on DOM after print call.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment