I need to print an specific DIV, but every other post I have seen doesn't include the styles within the DIV, is there a way to do this with one function in javascript?
I have already seen this and other posts Print the contents of a DIV
I need to print an specific DIV, but every other post I have seen doesn't include the styles within the DIV, is there a way to do this with one function in javascript?
I have already seen this and other posts Print the contents of a DIV
You can select all other elements and hide them from the page (excluding the target with the use of the :not()
CSS pseudo class), then call window.print()
to print the page:
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 want to create a function that accepts an element as a parameter, you can loop through all elements and check whether the current item being looped through is the parameter. If it isn't, 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>
Unfortunately, the function above hides children of the element, which can cause issues. We can counter this by checking whether the element looped through is included in the 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 unhide all the elements after printing, a lazy way to do it would be:
document.body.querySelector("*").forEach(e => e.style.display="none");
That will show hidden elements prior to printing
Here is a simple way to do so!
$('a.printPage').click(function(){
$('#report-summary').show();
window.print();
return false;
});
#report-summary {
}
@page { size: auto; margin: 25mm 25mm 25mm 25mm; }
@media print {
#search,
.printPage {
display: none !important;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" referrerpolicy="no-referrer"></script>
<div id="report-summary">
Content here ...
</div>
<div class="printbtn">
<a class="printPage" href="#">Print Report</a>
</div>