views:

35

answers:

3

The w3c validator service complains that the following html is invalid. It does not like the ampersand(&) in my javascript. But ampersands are allowed in javascript strings, aren't they?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
    <head>
        <title>Page Title</title>
    </head>
    <body>
        <script type="text/javascript">


           function search(query) {
             redir = "http://search.mysite.com/search?s=FIN&amp;ref=&amp;q=" + query;
             window.location.href = redir
             return false;
            }
        </script>

        <span>This is all valid HTML</span>

    </body>
</html>
+3  A: 

All browsers will take this, but to make it valid X(HT)ML you need to put the Javascript code in a CDATA block.

Bart van Heukelom
+1  A: 

Even in javascript w3c validator don't like ampersands. Try to comment your javascript from validator

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
    <head>
        <title>Page Title</title>
    </head>
    <body>
        <script type="text/javascript">
        //<![CDATA[//><!--
           function search(query) {
             redir = "http://search.mysite.com/search?s=FIN&amp;ref=&amp;q=" + query;
             window.location.href = redir
             return false;
            }
        //--><!]]>
        </script>

        <span>This is all valid HTML</span>

    </body>
</html>
antyrat
+1  A: 

No, it is indeed not valid. If you want to use in-line JavaScript in an XHTML file, you'll need to wrap the JavaScript in CDATA. If you don't want to do that, then you're stuck with encoding &, < and >, which in JavaScript can be quite a pain.

ErikHeemskerk