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">

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



  1. Frederick
    Permalink to comment#

    CDATA is a good friend of mine :)

    • CoryMathews
      Permalink to comment#

      I always assumed that was for older browsers, good to know its actual meaning.

  2. Joao Joaquim
    Permalink to comment#

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

  3. Jessi Hance
    Permalink to comment#

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

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

    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

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences like this:

  function example() {
    element.innerHTML = "<div>code</div>";

We have a pretty good* newsletter.