How to print only a selected HTML element?

Simple html and pure javascript works best. Parameter "this" refers to current id, so that function is universal for all ids. By using "ref.textContent" instead of "ref.innerHTML" you can extract only textual content for printing.

html body:

<div id="monitor" onclick="idElementPrint(this)">element to print
<img src="example.jpg" width="200">
</div>

pure javascript:

/*or:
monitor.textContent = "click me to print content";

const imga = new Image(200); //width
imga.src = "./example.jpg";
monitor.appendChild(imga);
*/

const idElementPrint = ref => {
  const iframe = document.createElement("iframe");
  iframe.style.display = "none";
  document.body.appendChild(iframe);
  const pri = iframe.contentWindow;
  pri.document.open();
  pri.document.write(ref.innerHTML);
  pri.document.close();
  pri.focus();
  pri.print();
  pri.onafterprint = () => { document.body.removeChild(iframe); }
}

Created something generic to use on any HTML element

HTMLElement.prototype.printMe = printMe;
function printMe(query){
  var myframe = document.createElement('IFRAME');
  myframe.domain = document.domain;
  myframe.style.position = "absolute";
  myframe.style.top = "-10000px";
  document.body.appendChild(myframe);
  myframe.contentDocument.write(this.innerHTML) ;
  setTimeout(function(){
  myframe.focus();
  myframe.contentWindow.print();
  myframe.parentNode.removeChild(myframe) ;// remove frame
  },3000); // wait for images to load inside iframe
  window.focus();
 }

Usage:

document.getElementById('xyz').printMe();
document.getElementsByClassName('xyz')[0].printMe();

Hope this help
Regards
Gaurav Khurana


You could use a print specific CSS stylesheet and hide everything but what you want printed.

<div class="no-print">I won't print</div><div class="something-else">I will!</div>

Just the no-print class will be hidden, but anything with a print class will show.

<style type="text/css" media="print">
   .no-print { display: none; }
</style>

If you are familiar to jQuery, you can use jQuery Print Element plugin like this:

$('SelectorToPrint').printElement();