javascript document.write css does not apply

advertisements

HTML:

<div id="dvContainer">
        This content needs to be printed.
</div>
<button>Print</button>

JavaScript:

 $("button").on("click", function(){
    var divContents = $("#dvContainer").html();
            var printWindow = window.open('', '', 'height=400,width=800');
            printWindow.document.write('<html><head><title>DIV Contents</title>');
            printWindow.document.write("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/product.css\" />");
            //printWindow.document.write("<style>#dvContainer{color: red;}</style>");

            printWindow.document.write('</head><body>');
            printWindow.document.write(divContents);
            printWindow.document.write('</body></html>');
            printWindow.document.close();
            printWindow.print();
});

I need my div to change to red when the window appears, but nothing happened.

I tried using style code but my element is still black. I also tried the media print but nothing.

Any suggestions please? What am I doing incorrectly?
I'm testing this in the latest version of Chrome, and jQuery 1.9.1.


After our conversation what you want to do is to setup the print styles properly. Add this to products.css

@media print {
   body {
      background-color: red;
   }
 }