Liam
Liam

Reputation: 281

How to style div classes that are stored in a JS variable?

I am trying to print a series of divs shown on a page. The divs are stored in a parent ('printDialog') and is being stored as 'prtContent', to be presented in a new window.


        $(document).on("click","#modalBtnPrint",function() {
            var prtContent = document.getElementById("printDialog").innerHTML;
            var WinPrint = window.open('', '', 'right=0,top=0,width=800,height=900,toolbar=0,scrollbars=0,status=0');
            if(WinPrint != null) {
                WinPrint.document.write(prtContent);
            }
            WinPrint.focus();
            WinPrint.print();
            WinPrint.close();
    });

My questions is:

Edit:

With the help of T.Chmelevskij this is what I got to work:

$(document).on("click","#modalBtnPrint",function() {
        var prtContent = document.getElementById("printDialog").innerHTML;
        var WinPrint = window.open('', '', 'left=0,top=0,width=800,height=900,toolbar=0,scrollbars=0,status=0');
        if(WinPrint != null) {
            WinPrint.document.write(prtContent);
            var x = WinPrint.document.querySelectorAll(".update");
            for (i = 0; i < x.length; i++) {
                x[i].style.borderStyle = "solid";
            }
            var x = WinPrint.document.querySelectorAll(".required");
            for (i = 0; i < x.length; i++) {
                x[i].style.fontWeight = "bold";
            }
        }
        WinPrint.document.close();
        WinPrint.focus();
        WinPrint.print();
        WinPrint.close();
    });

Thank you everyone!

Upvotes: 0

Views: 432

Answers (2)

sumit chauhan
sumit chauhan

Reputation: 1300

If you want to append style from a variable you can use the following code:

var style = document.createElement('style');
style = **your variable which store css**
document.head.append(style);

this will apend your css on click on button. as well as no other css can override you css.

Upvotes: 0

T.Chmelevskij
T.Chmelevskij

Reputation: 2139

Your WinPrint variable holds reference to desired window. So something like:

WinPrint.window.document.querySelector('body').style.backgroundColor = "red";

Works.

But as @epascarello mentioned, if it's just for styling print output then css '@media' queries for printing is the best solution.

Upvotes: 1

Related Questions