PSD to HTML conversion PSD to HTML conversion PSD2HTML.com with over 300 professionals takes the designs to HTML and beyond

Code Snippet

Home » Code Snippets » JavaScript » Prevent Embedded JavaScript from Failing Validation

Prevent Embedded JavaScript from Failing Validation

Ever see that CDATA stuff in JavaScript and wonder what it was for? It is to prevent the validator from reading that code as markup and failing validation. For example, ampersands (&) and greater-than / less-than signs (< >)are often culprits for failing validation when it's actually perfectly OK to use them in JavaScript.

<script type="text/javascript">
  //<![CDATA[

    alert("<This is compatible with XHTML>");

  //]]>
</script> 

Subscribe to The Thread

  1. CDATA is a good friend of mine :)

  2. I had this doubt some time ago an googled it to find out.

  3. Thank you! I always did wonder. Now I’ll use it!

  4. I did wonder that! I’m also liking the site’s new look. I haven’t been here for a while and it’s totally different!

  5. =), thx chris for this hint…I had this issue several times (not validation xhtml because of markup in the js btw. elements that were appended and were hard-coded in the js)…I just outplaced the code in an external .js file and the error has gone but now I know what to do next time!

  6. I think this snippet is a little misleading. The use of “validating” makes it sound like marking blocks as CDATA is only useful if you “want your pages to validate.” Whereas validate in this case actually means, “if you want your pages to render properly.”

  7. This is one of those facepalm moments for me, I’m afraid. I had precisely this problem not long ago, with embedded JavaScript causing a load of validation errors.

    I would up moving it to an external .js file, which worked better anyway, but next time I’ll know! Thanks Chris!

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~