Reputation: 154
I want to generate printing innerHTML elements of a div
by javascript, so I wrote some code based on these answers. But I want to add another function: I want the printed elements to include not only the innerHTML of the div
but its css from <stylesheet>
as well. So I modified the code as below, but it doesn't seem to be working well.
<style>
#divID {
some css...
}
<style>
function printdiv() {
var headstr = "<html><head><title>file_name</title></head><body>";
var footstr = "</body></html>";
var newstrstyle = document.getElementsByTagName("style")[0].innerHTML; // is this right?
var newstr = document.getElementById('divID').innerHTML;
var oldstr = document.body.innerHTML;
document.body.innerHTML = headstr + '<style>' + newstrstyle + '</style>' + newstr + footstr;
window.print();
document.body.innerHTML = oldstr;
return false;
}
I want to bring the CSS from stylesheet instead of adding style values into the string, because what I'm working on has editable css. How should I improve the code?
Upvotes: 1
Views: 827
Reputation: 1
<style media="print">
body>*:not(.mydiv){
display: none;
}
.mydiv{display: block;}
</style>
or this in ref css file if link to outer css
@media print{
body>*:not(.none){
display: none;
}
.none{display: block;}
}
function printDiv{window.print()}
<style>.mydiv{display: none;}</style>
Upvotes: 0
Reputation: 2715
The problem is that newstr
contains the content of the div
, but the div
with the id
"divID"
itself not. It follows that the #divID
css selector won't match to any div
-s, so the styles will not be applied.
To fix this the "<div id='divID'>"
itself needs to be added, so the fixed function looks following:
function printdiv() {
var headstr = "<html><head><title>file_name</title></head><body>";
var footstr = "</body></html>";
var newstrstyle = document.getElementsByTagName("style")[0].innerHTML; // is this right? -> yes it is
var newstr = document.getElementById("divID").innerHTML;
var oldstr = document.body.innerHTML;
document.body.innerHTML =
headstr +
"<style>" +
newstrstyle +
"</style>" +
"<div id='divID'>" + // this div was missing
newstr +
"</div>" + // closing the added div
footstr;
window.print();
document.body.innerHTML = oldstr;
return false;
}
If you want to check a live example, here is the stackblitz code where I figured it out: https://stackblitz.com/edit/js-madufb?file=index.js
Upvotes: 2