Grow your CSS skills. Land your dream job.

Last updated on:

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> 

Comments

  1. Permalink to comment#

    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. amy
    Permalink to comment#

    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. LuK
    Permalink to comment#

    =), 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!

Leave a Comment

Posting Code

  • Use Markdown, and it will escape the code for you, like `<div class="cool">`.
  • Use triple-backticks for blocks of code.
    ``` 
    <div>
      <h1>multi-line block of code</h1>
      <span>be cool yo.</span>
    </div>
    ```
  • Otherwise, escape your code, like <code>&lt;div class="cool"&gt;</code>. Markdown is just easier though.

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".