0

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.

3
  • I don't mean to ask the obvious but what does the DTD you're checking against say about where your div can and can't be? Commented Jul 17, 2013 at 9:39
  • I added <!DOCTYPE> to the question. Commented Jul 17, 2013 at 9:44
  • "Obviously the parser assumes that <span> is nested inside <script>" - I doubt that. Commented Jul 17, 2013 at 10:26

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

1 Comment

You are right. I updated the example to use div instead of pre. the problem is still the same
1

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.

1 Comment

You are right. I updated the example to use div instead of pre. the problem is still the same

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.