Forum Moderators: open
Does anyknow know how to do this and make it xhtml 1.1 compliant?
<script type="text/javascript">
for( i=0 ; i<len ; i++) {
blah blah blah;
}
</script>
When it gets to the i<len part, the validator gives me an error:
element "len" undefined.
...put the script back in. It is a no win situation as far as I know.
Well, it depends if it is important that your page is true XHTML and not simply HTML.
The validator is correct, in that you cannot embed unescaped script (as you are doing using '<' and '&' etc.) in your XHTML pages. The thing is with XHTML is if it doesn't validate then it's not XHTML! In a strict sense. The browser, however, is likely to be handling this by displaying it as HTML, not XHTML.
This is a big difference between XHTML and HTML. In HTML your script is considered CDATA (character data), in XHTML it's PCDATA (Parsed Character Data). The XHTML processor treats '<' and '&' etc. as markup.
You have a few options...
[1] Use HTML instead. (Why most of us should NOT use XHTML [webmasterworld.com])
[2] Move your JS into an external JS file and perhaps call it from the windows.onload event. It is always good practise to have your JS in an external file... separating your content and behaviours.
[3] If you only have a line or two of script then you can enclose your script in a CDATA section (to avoid it being parsed by XHMTL). (See [w3.org...]
<![CDATA[
.....
]]>
<script type="text/javascript">
//<![CDATA[
for( i=0 ; i<len ; i++) {
blah blah blah;
}
//]]>
</script>
Please check it - I've not tried this recently.
I'm sure I've seen/used far more complicated escapes in the past, although this I suspect was to accommodate very old browsers (which most of us can now ignore?) which required the use of HTML comments <!-- --> (in addition to those mentioned) to hide the script from browsers that didn't even acknowledge the script tag.
Useful (Mozilla) resource...
Properly_Using_CSS_and_JavaScript_in_XHTML_Documents [developer.mozilla.org]