0

I'm getting an odd HTML validation error from this piece of JavaScript any help appreciated, I think it may be causing a bug in the slider function that I'm working with...

<script type="text/javascript" charset="utf-8">
        sfHover = function() {
            var sfEls = document.getElementById("nav2").getElementsByTagName("LI");
            for (var i=0; i<sfEls.length; i++) {
                sfEls[i].onmouseover=function() {
                    this.className+=" sfhover";
                }
                sfEls[i].onmouseout=function() {
                    this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
                }
            }
        }
        if (window.attachEvent) window.attachEvent("onload", sfHover);
    </script>

The errors are

Error: character ";" not allowed in attribute specification list

and

Error: element "sfEls.length" undefined

from the line

for (var i=0; i

and

Error: end tag for "sfEls.length" omitted, but OMITTAG NO was specified

from the closing script tag

1

1 Answer 1

6

Your Javascript contains special characters for XML (< and &).
Therefore, it's invalid markup.

You need to wrap it in a CDATA section, which will prevent the XML parser from parsing its contents:

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

The comments are necessary to prevent the CDATA section from causing Javascript syntax errors in browsers that don't recognize it

Sign up to request clarification or add additional context in comments.

6 Comments

@SLaks, I was under the impression that only the end comment was necessary, because the parser won't pass the CDATA start tag to the script engine (and the same applies to the HTML comments that are sometimes used instead). Am I misguided?
@Frédéric: You're assuming an XML-aware browser. IE, I believe, will do none of that.
@SLaks, indeed, I was (wrongly) assuming that HTML somehow inherited CDATA sections from SGML. Thanks for your clarification :)
@SLacks - do you think the absence of the cdata markup would cause odd behaviour in a mootools slider - or is this simply a function of the validator I'm using?
@too: It won't cause any issues at all; it just makes the markup invalid. All browsers will handle it fine.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.