Matt Ledger
Matt Ledger

Reputation: 213

Validate loading CSS with JavaScript

I have two style sheets, one default style and one Christmas style. I would like the Christmas style to be loaded in December and the default to be used in every other month.

I have written the code below which achieves what I want, however if I put it in to a validator I get the error: "document type does not allow element "link" here". I was wondering how I could make this code validate?

<head>
    <script type="text/javascript">
        var i = new Date();
        var m = i.getMonth();
        if (m==11) {
            document.write('<link rel="stylesheet" type="text/css" href="mystyle-christmas.css" />');
        } else {
            document.write('<link rel="stylesheet" type="text/css" href="mystyle-default.css" />');
        }
    </script>
</head>

Upvotes: 0

Views: 447

Answers (2)

Florian Margaine
Florian Margaine

Reputation: 60747

The validator has problems because you're not using CDATA, thus the validator will parse your javascript. Use the following to solve your problem:

<head>
    <script>
    //<![CDATA[
        // Your code here
    // ]]>
    </script>
</head>

Btw, the following is a better way to do it:

<head>
    <script type="text/javascript">
        var i = new Date(),
            m = i.getMonth(),
            l = document.createElement( 'link' )

        l.rel = 'stylesheet'

        if ( m === 11 ) {
            l.href = 'mystyle-christmas.css'
        }
        else {
            l.href = 'mystyle-default.css'
        }

        document.getElementsByTagName( 'HEAD' )[ 0 ].appendChild( l )
    </script>
</head>

And an even better way is to have your javascript in an external js file.

Upvotes: 3

Jivings
Jivings

Reputation: 23250

Try creating the element instead of using document.write:

  var christmas = document.createElement("link");
  christmas.setAttribute("rel", "stylesheet");
  christmas.setAttribute("type", "text/css");
  christmas.setAttribute("href", "mystyle-christmas.css");

  document.getElementsByTagName("head")[0].appendChild(christmas)

Upvotes: 0

Related Questions