Question

I have a web page that generates HTML via JavaScript.

When validating using HTML validator 0.9.5.1 in Firefox 22, I get an error: 'document type does not allow element "span" here'

I am using this JavaScript:

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 ...<body>...
 <script type='text/javascript'>
var someHtml = '<span>Hello world!</span>';
var e;
e = window.document.createElement('div');
e.innerHTML = someHtml;
window.document.body.appendChild(e);
 </script>

Obviously the parser assumes that <span> is nested inside <script>

How should i rewrite the JavaScript to pass HTML validation? I would prefer a solution that does not require me to create HTML elements.

Note: The answers in Avoiding HTML-in-string / html() in a jQuery script do not help me since I know that the code works. I want to reformat to avoid validation errors.

Was it helpful?

Solution

the pre element is for preformatted text, not more HTML.

HTML Tidy's objection is that you are putting something that it believes you expect the browser to render as HTML, you need to scape the entities (replacing < and > with &lt; and &gt;) so that it is interpretted as text.

UPDATE IN RESPONSE TO COMMENT: With an XHTML doctype, the document must be wellformed XML. So, you need CDATA marks inside your script tag:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <title>Hello world</title>
  </head>
  <body>
  <script type='text/javascript'>
  //<![CDATA[
  var someHtml = "<div>Hello world!</div>";
  var e;
  e = window.document.createElement('div');
  e.innerHTML = someHtml;
  window.document.body.appendChild(e);
  //]]>
  </script>
  </body>
</html>

OTHER TIPS

You can't put <div> inside <pre>. <pre> can contain phrasing content only, where <div> is not.

Also you should wrap your script with <![CDATA[ ... ]]> section since doctype is XHTML.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top