Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: How do fix W3 Validation Error caused by &

Is there any way to fix the error that a JavaScript & causes in w3 validation? The problem is that i have to use && in a if statement and these two &&'s causes errors in w3 validation.

EDIT: Same problem with "<" and ">".

like image 773
Poku Avatar asked Sep 27 '09 10:09

Poku


2 Answers

There are a few things you can do.

You can enclose it within HTML comments:

<script type="text/javascript">
<!--

if (foo && bar) ...

//-->
</script>

You can enclose it in a CDATA section:

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

if (foo && bar) ...

// ]]>
</script>

You can include in in a file instead:

<script src="foobar.js" type="text/javascript"></script>
like image 120
Greg Avatar answered Oct 04 '22 22:10

Greg


The primary answer is: Use JavaScript files for JavaScript, not HTML files, and use the src attribute of script tags. (Combine all your JS into one file, minimize, gzip, etc. for performance.)

But, you can embed JavaScript in HTML if absolutely necessary. Use a valid, modern DOCTYPE and you don't have to resort to comment tags and CDATA sections.

Valid HTML5 example:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Example</title>
<script type='text/javascript'>
function foo() {
   var a = 1, b = 2;

   if (a && b) {
      alert("Both");
   }
   if (a < b) {
      alert("a < b");
   }
   if (a > b) {
      alert("a > b");
   }
}
</script>
</head>
<body>
<p>Hi there</p>
</body>
</html>

That will also validate as HTML4 strict if you change the doctype to

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

Note that in both cases, you need to be careful about end tags in your script --

This causes the problem:

<script type='text/javascript'>
alert("</td>");
</script>

This solves the problem by prefacing the slash with a backslash (or you can break the end tag up into separate string literals):

<script type='text/javascript'>
alert("<\/td>");
// -or-
alert("<" + "/td>");
</script>

But again, the basic answer is: Don't embed JavaScript within HTML files when you can avoid it, use JavaScript files for that.

like image 23
T.J. Crowder Avatar answered Oct 04 '22 20:10

T.J. Crowder