Using JavaScript with XHTML

The XHTML DTD defines the Script elements as #PCDATA. Therefore the < sign, the ampersand (&) and other characters contained in Scripts (e.g. JavaScript) will be interpreted as entity references. To avoid this interpretation one must wrap the content of our Scripts within a CDATA marked selection. This condition applies for Scripts written in any language, not just JavaScript. Alternatively, you can use external Scripts.

Using JavaScript in XHTML documents

Using an External JavaScript file in XHTML

 

Using JavaScript in XHTML documents

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
   PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script language="JavaScript">
   <![CDATA[
   function showMsg() {
      if (1<2 && 1>0)
         window.alert('1 is a positive number smaller than 2');
   }
   ]]>
</script>
<title>Using XHTML with JavaScript</title>
</head>
<body>
<h2>Using XHTML with JavaScript</h2>
<p><a href="JavaScript:showMsg()"> Find out if 1 is smaller than 2</a></p>
</body>
</html>

Note that good-old HTML Script hiding (example below) will not work.

<script language="JavaScript">
   <-- Hide from Old Browsers...
   ... Script Contents ...
   // This only worked for HTML -->
</script>

Top of Page

 

Using an external JavaScript file in XHTML

If you call an external Script file, you don't have to worry about adding anything special to either the calling file or the external file. A sample call to an external Script file follows:

<head>
<title>Using JavaScript with XHTML</title>
   <script language="JavaScript" src="myjavascriptfile.js">
   </script>
</head>

Top of Page

Valid XHTML 1.0! Valid CSS!