Introduction

Although valid in HTML, the following code block is invalid in XHTML:

<script type="text/javascript"> 
    function compare(a, b) { 
        if (a < b) { 
            console.log("A is less than B"); 
        }
    } 
</script> 

In HTML, the <script> element has special rules governing how its contents should be parsed.

In XHTML, the less-than symbol (<) in the statement a < b is interpreted as the beginning of a tag.

You can replace all occurrences of the less-than symbol (<) with its HTML entity (&lt;).

<script type="text/javascript"> 
    function compare(a, b) { 
        if (a &lt; b) { 
            console.log("A is less than B"); 
        }
    } 
</script> 

Or you can wrap the JavaScript code in a CDATA section.

In XHTML CDATA sections indicates free-form text. This enables you to use any character, including the less-than symbol. The format is as follows:

<script type="text/javascript"><![CDATA[ 
    function compare(a, b) { 
        if (a < b) { 
            console.log("A is less than B"); 
        } 
    } 
]]></script>  

In non-XHTML-compliant browser, the CDATA markup must be offset by JavaScript comments:

<script type="text/javascript"> 
//<![CDATA[ 
    function compare(a, b) { 
        if (a < b) { 
            console.log("A is less than B"); 
        } 
    } 
//]]> 
</script>  

Related Topic