Re: embedded end tag errors

2013-07-11 19:38, Ken Jones wrote:

> When an end tag such as </style> or </a> is found in an embedded usage,
 > as below, it flags it as an error because it found an unattached tag.

The issue is really that inside a script element, any end tag will be 
treated as a syntax error, when using HTML 4.01 validation. The content 
model of <script> is CDATA, and:
"The first occurrence of the character sequence "</" (end-tag open 
delimiter) is treated as terminating the end of the element's content. 
In valid documents, this would be the end tag for the element."
http://www.w3.org/TR/REC-html40/types.html#type-cdata

HTML5 does not have this rule, which is really just a theoretical rule 
imposed by formal specifications and hence by the validator.

> I can get around it by using the following hack
>
> <script type="text/javascript">
> if (isTouchDevice()) {
> document.write( "<style type='text/css'>");
> ..... some stuff in here ...
> document.write( '<' + "/style>"); // this now works, and the page is completely functional
> };
> </script>

Such a "hack" is one way of avoiding the formal problem. Another one, 
mentioned at
http://www.w3.org/TR/REC-html40/appendix/notes.html#h-B.3.2
is to prefix the "/" in "</style>" by the backslash "\". JavaScript 
interpreters will take "\/" as denoting "/", and this is a way of 
"escaping" HTML parsing (which parses </style> as tag, but not <\/style>).

Usually the best approach is to put JavaScript code to an external file 
and <link> to it. This way, it will not be parsed as HTML at all.

Some people would add that instead of document.write, you should 
manipulate the DOM tree, using document.createElement to create an 
element node and then add it to the tree. This, too, would avoid the 
issue, since your JavaScript code would not contain any HTML tags, just 
element names like 'style'.

Yucca

Received on Friday, 12 July 2013 10:24:53 UTC