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?