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

    CDATA is a good friend of mine :)

    • User Avatar
      Permalink to comment#

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

  2. User Avatar
    Joao Joaquim
    Permalink to comment#

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

  3. User Avatar
    Jessi Hance
    Permalink to comment#

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

  4. User Avatar
    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. User Avatar
    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. User Avatar
    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. User Avatar
    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!

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.