andrii
andrii

Reputation: 727

How can I place HTML in a JavaScript string and have it validate?

I want to show different css files depending on browser that user is using. I want to do this on JS and on client side. I am using code like this.

 <script language="javascript" type="text/javascript">
 if ((navigator.userAgent.indexOf("MSIE")) >= "0"){
    document.write("<link rel=\"stylesheet\" href=\"css/common.IE.css\" type=\"text/css\" 
 }
 if ((navigator.userAgent.indexOf("Chrom")) >= "0"){
    document.write("<link rel=\"stylesheet\" href=\"css/common.chrome.css\" type=\"text/css\" />");
 }

*The only problem that I this code is not valid. How I can solve the problem. If I check this document with w3 checker. it will show now: Line 22, Column 90: document type does not allow element "link" here*****

…nt.write("<link rel='stylesheet' href='css/common.IE.css' type='text/css' />");

Line 25, Column 35: an attribute value must be a literal unless it contains only name characters

document.write("<link rel=\"stylesheet\" href=\"css/common.chrome.css\"…

Upvotes: 1

Views: 351

Answers (3)

meder omuraliev
meder omuraliev

Reputation: 186762

Bad idea. Can you tell us your real issues which are causing you to serve different stylesheets to different browsers?

You should strive to serve all browsers with one stylesheet, and maybe an additional to IE with CondComs ( sounds like condoms ).

Upvotes: 3

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196306

break it up in sub-strings so that it does not get detected ..

document.write("<l" + "ink ...

or add comments like this

<script type="text/javascript">
//<!--

if ((navigator.userAgent.indexOf("MSIE")) >= "0"){
    document.write("<link rel=\"stylesheet\" href=\"css/common.IE.css\" type=\"text/css\" 
 }
 if ((navigator.userAgent.indexOf("Chrom")) >= "0"){
    document.write("<link rel=\"stylesheet\" href=\"css/common.chrome.css\" type=\"text/css\" />");
 }


//-->
</script>

Upvotes: 2

alex
alex

Reputation: 490667

Wrap that block in CDATA tags.

So it looks like like...

<script language="javascript" type="text/javascript">
<![CDATA[
 if ((navigator.userAgent.indexOf("MSIE")) >= "0"){
    document.write("<link rel=\"stylesheet\" href=\"css/common.IE.css\" type=\"text/css\" 
 }
 if ((navigator.userAgent.indexOf("Chrom")) >= "0"){
    document.write("<link rel=\"stylesheet\" href=\"css/common.chrome.css\" type=\"text/css\" />");
 }
]]>
<script>

Upvotes: 3

Related Questions