To hide all elements on the page except for a specific target, you can use the :not()
CSS pseudo-class to select and hide them, then trigger the printing of the page by calling window.print()
:
btn.addEventListener('click', function(){
document.body.querySelectorAll(':not(.red)').forEach(e => e.style.display = "none");
window.print();
})
div{
height:100px;
border:1px solid;
}
.red{
background-color:red;
}
.blue{
background-color:blue;
}
<div class="red">
red
</div>
<div class="blue">
blue
</div>
<button id="btn">Print Red div</button>
If you need to create a function that takes an element as an argument, you can iterate through all elements and compare each one to the parameter. If it doesn't match, hide the element:
Demo:
btn.addEventListener('click', function(){
printWithStyles(document.querySelector('.red'));
})
function printWithStyles(e){
document.body.querySelectorAll("*").forEach(f => f === e ? '' : f.style.display="none");
window.print();
}
div{
height:100px;
border:1px solid;
}
.red{
background-color:red;
}
.blue{
background-color:blue;
}
<div class="red">
red
</div>
<div class="blue">
blue
</div>
<button id="btn">Print Red div</button>
However, the above function hides children of the specified element, which may lead to problems. To avoid this, we can modify the function to check if an element is contained within the specified parameter:
btn.addEventListener('click', function(){
printWithStyles(document.querySelector('.red'));
})
function printWithStyles(e){
document.body.querySelectorAll("*").forEach(f => e.contains(f) ? '' : f.style.display="none");
window.print();
}
div{
height:100px;
border:1px solid;
}
.red{
background-color:red;
}
.blue{
background-color:blue;
}
<div class="red">
<h1>red</1>
</div>
<div class="blue">
blue
</div>
<button id="btn">Print Red div</button>
To show all hidden elements after printing, a simple method would be:
document.body.querySelector("*").forEach(e => e.style.display="none");
This will reveal any previously hidden elements before printing.