JSFiddle - React, Tailwind, and code Playground

by Amir Sharifian

HTML

<div>
  This should NOT be printed!
<button id="btnPrint">Print (this button should also be NOT be printed)!</button>
</div>

<hr />

<div id="printThis">
    This should BE printed!
</div>

<div id="printThisToo">
    This should BE printed, too!
</div>

CSS

@media screen {
  #printSection {
      display: none;
  }
}

@media print {
  body * {
    visibility:hidden;
  }
  #printSection, #printSection * {
    visibility:visible;
  }
  #printSection {
    position:absolute;
    left:0;
    top:0;
  }
}

JavaScript

document.getElementById("btnPrint").onclick = function() {
    printElement(document.getElementById("printThis"));
    printElement(document.getElementById("printThisToo"), true, "<hr />");
    window.print();
}

function printElement(elem, append, delimiter) {
    var domClone = elem.cloneNode(true);

    var $printSection = document.getElementById("printSection");

    if (!$printSection) {
        var $printSection = document.createElement("div");
        $printSection.id = "printSection";
        document.body.appendChild($printSection);
    }

    if (append !== true) {
        $printSection.innerHTML = "";
    }

    else if (append === true) {
        if (typeof(delimiter) === "string") {
            $printSection.innerHTML += delimiter;
        }
        else if (typeof(delimiter) === "object") {
            $printSection.appendChlid(delimiter);
        }
    }

    $printSection.appendChild(domClone);
}