Thalatta Thalatta - 1 year ago 58
CSS Question

document.write() for adding a stylesheet causes document to be blank

I am trying to add a stylesheet only on the condition that the browser is either Chrome or Opera. I have the following control flow using the YUI library:

if (( > 0) || (Y.UA.opera > 0)){
document.write("<link rel='stylesheet' media='print' type='text/css' href='../../../css/style_ticket_printing_header.css'/>");

Here is the conditionally attached css file,

size: auto;
margin: 0mm;

Here is the full HTML:

When I run the page in Chrome, none of the
s that are defined within the
tag are rendered or are displayed within the DOM.

What is particularly confusing is that, when this CSS is loaded in the normal way (by simply referencing it via a
tag in the
of the page, all of the DOM are loaded perfectly.

And finally I know that it successfully renders the condition of seeing it is chrome as I formerly had an alert message in the body of the if block which successfully executed.

Answer Source

document.write() for adding a stylesheet causes document to be blank

Right. When you use document.write after the main page parsing is complete, it implicitly does a, which wipes out the page.

Instead, use createElement and appendChild:

if (( > 0) || (Y.UA.opera > 0)){
    var link = document.createElement('link');
    link.rel = "stylesheet"; = "print";
    link.type = "text/css";
    link.href = "../../../css/style_ticket_printing_header.css";

Or if you really like to use HTML: :-)

if (( > 0) || (Y.UA.opera > 0)){
        "<link rel='stylesheet' media='print' type='text/css' href='../../../css/style_ticket_printing_header.css'/>"

(Both of the above assume you have a head element, which you presumably do; it's required in a well-formed HTML document, either explicitly or because the browser adds it for you [but explicit is best].)

About querySelector: It finds the first element that matches a CSS selector. It's supported by all modern browsers, and also IE8. (There's also querySelectorAll, which finds a list of matching elements.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download