简体   繁体   中英

html generation via javascript: avoiding htmltidy error

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.

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM