Blair Anderson
Blair Anderson

Reputation: 20171

Can you prevent innerHTML from removing HTML, HEAD, BODY elements?

I am trying to implement a wysiwyg into an app, they all use contentEditable which is cool until i put an entire html document into a text box. Each wysiwyg uses html() and innerHTML to move the content around and both of these strip , , and tags...

html = "<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <title>Title</title>
  </head>
  <body>
    <span>Hey There</span>
  </body>
  </html>
  "

editable.innerHTML = html
editable.innerHTML
// => "
  <meta http-equiv="Content-type" content="text/html; charset=utf-8">
  <title>Title</title>
  <span>Hey There</span>
"

same exact thing happens with $(editable).html(). I cannot find spec regarding this.

what do?

Upvotes: 0

Views: 780

Answers (1)

loganfsmyth
loganfsmyth

Reputation: 161457

An HTML document can only have a single html, body and head element, and your main page already has those. It is stripping it out because you are trying to insert them in positions that are not allowed.

You'd either have to strip those out entirely and then add them back on after the element content is edited, or put your entire WYSIWYG editor inside an iframe element so that you have the whole iframe document to work with rather than a single element.

It is documented, though you kind of need to know what you are looking for. See the <body> docs on MDN:

Permitted parent elements: It must be the second element of an element.

and from the docs for <html>:

Permitted parent elements: As the root element of a document, or wherever a subdocument fragment is allowed in a compound document.

Upvotes: 2

Related Questions