2

I have some javascript that is embedded in the html file like this

<html>
    <head>
        <script>
            // and the script runs here
        </script>
    </head>
    <body></body>
</html>

And it has a line like this

if((os == 'Mac')&&((br == 'Safari')||(br == 'Chrome')))

Everything goes OK (which means the script works), but the validator is screaming:

... character "&" is the first character of a delimiter but occurred as data
... This message may appear in several cases:
-You tried to include the "<" character in your page: you should escape it as "<"
-You used an unescaped ampersand "&": this may be valid in some contexts, but it is recommended to use "&", which is always safe.
-Another possibility is that you forgot to close quotes in a previous tag.

It seems ridiculous to replace all & with &amp. How can I get rid of that error?

1 Answer 1

5

If you are using XHTML, you need to enclose your inline scripts within a CDATA section:

<script type="text/javascript">
// <![CDATA[
    document.write("&");
// ]]>
</script>

Further reading:

Sign up to request clarification or add additional context in comments.

4 Comments

hell yeah thanks. and it seems funny that i have to escape the <![CDATA[ thing
That's because you are trying to write something that is both XHTML and close enough to HTML to work when you tell browsers that it is text/html instead of application/xhtml+xml. It is more effort then it is worth IMO so I stick to writing HTML 4.01.
...I still use XHTML, but stick to external scripts for any significant amount of code. Either way, avoid explicit browser-sniffing.
@bobince: I wouldn't, but the designer made that so I better just leave it alone :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.