2

I am running my site through the W3C HTML Validator (http://validator.w3.org/), although I am getting a very odd error.

This is the error copied word for word:

 Line 31, Column 29: character "&" is the first character of a delimiter but occurred as data
if( pageName != "blog.html" && pageName != "blog" ) {
✉
This message may appear in several cases:

You tried to include the "<" character in your page: you should escape it as "&lt;"
You used an unescaped ampersand "&": this may be valid in some contexts, but it is recommended to use "&amp;", which is always safe.
Another possibility is that you forgot to close quotes in a previous tag.

This is just a very small piece of Javascript within the <head> of my site. This is the code:

<script type="text/javascript">
var pathName = window.location.pathname;
var pageName = pathName.substr( pathName.lastIndexOf("/") + 1 );

if( pageName != "blog.html" && pageName != "blog" ) {
    document.write("<style type='text/css'>#article_intro_ag { display:none; } </style>");
}
</script>

Does anyone have any suggestions to why this is being displayed as an error within a HTML validator?

EDIT: This error occurs twice, for both & symbols.

Fizzix
  • 23,679
  • 38
  • 110
  • 176
  • 2
    You probably have an error in code just before this snippet which is your real error. – John Conde Jan 02 '14 at 02:04
  • @JohnConde - I considered that, although above this snippet are other external Javascript and CSS documents being referenced. I have double checked, and they are all being called absolutely fine. – Fizzix Jan 02 '14 at 02:06

2 Answers2

3

This caused by validating against XHTML - XHTML, being XML, doesn't/can't make special CDATA amends for [script] elements.

It is valid as HTML (4 or 5) - in fact, encoding the characters as suggested will break the JavaScript in an HTML context!

This issue can be resolved by:

  • Ensuring the server sends the HTML (not XHMTL/XML) Content-Type and/or;
  • Using an HTML doctype (e.g. <!DOCTYPE HTML>) or;
  • Explicitly telling the validator to check against HTML or;
  • Writing valid XHTML, if the source is indeed XHTML

In summary: XHTML is not HTML.

user2864740
  • 60,010
  • 15
  • 145
  • 220
1

Try putting your javascript inside a CDATA block like this:

<script type="text/javascript">
<![CDATA[
// content of your Javascript goes here
]]>
</script>

which should make it pass validation. To be extra safe you can add Javascript comments around the CDATA tags to hide them from older browsers who don't understand the CDATA tag:

<script type="text/javascript">
/* <![CDATA[ */
// content of your Javascript goes here
/* ]]> */
</script>

I admit, this answer is "borrowed" from: How do I escape an ampersand in a javascript string so that the page will validate strict?

Community
  • 1
  • 1
Tiago
  • 1,984
  • 1
  • 21
  • 43