JSFiddle - React, Tailwind, and code Playground
by Neeraj
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>
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"));
};
function printElement(elem) {
var domClone = elem.cloneNode(true);
var $printSection = document.getElementById("printSection");
if (!$printSection) {
var $printSection = document.createElement("div");
$printSection.id = "printSection";
document.body.appendChild($printSection);
}
$printSection.innerHTML = "";
$printSection.appendChild(domClone);
window.print();
return false;
}