Replacing document.documentElement.innerHTML in Internet Explorer

The following works flawlessly (as far as I can tell) in all other browsers:

document.documentElement.innerHTML = "<head></head><body>Testing</body>";

But chokes in IE (I tested IE9), with a console error:

  • Get InnerHTML of element that isnt inside another tag
  • JQuery html() vs. innerHTML
  • Uncaught RangeError: Maximum call stack size exceeded with innerHTML
  • Why does html() execute JavaScript, but innerHTML doesn't?
  • Accessing properties hidden by __defineGetter__/__defineSetter__ in JavaScript
  • Can scripts be inserted with innerHTML?
  • SCRIPT600: Invalid target element for this operation. 

    …referencing the first character of the line of code above.

    Why won’t this work in IE, but will work in all other browsers? I read somewhere that innerHTML has issues replacing ‘TBODY’ elements, but I tested this line of code after removing all TBODY children and the same error occurred.

    I know this sounds like bad-news-code, but it is the only option I have left with the very limited and simplistic CMS website we are being forced to use. I’m only thankful that the CMS allows scripts to be executed.

    In essence, I need to be able to completely gut the HTML contents and use my own. Again, this works fine on other browsers.

    Other notes:

    • The CMS is using the prototype.js library (it’s already loaded before I run this code)
    • The Doctype is: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
    • The CMS scripts use prototype.js to dynamically add two divs full of content at page load

  • Add to innerHTML without destroying form contents
  • Inner workings of innerHTML
  • CSS/JavaScript: get user-visible text of an element
  • How to stop an automatic refresh using JS
  • IE removes option tags created with javascript
  • Execution of dynamically generated Javascript
  • One Solution collect form web for “Replacing document.documentElement.innerHTML in Internet Explorer”

    As both @duri and I confirmed, the documentElement (<html>) object along with a handful of other certain HTML elements are read-only in Internet Explorer (see link in first comment), and therefore replacing the documentElement in a cross-browser fashion is not possible.

    Using Javascript to strip all existing link and script tags from the head, then to set the body attributes to match the replacement content, then to replacing the innerHTML of the body, and finally dynamically adding my own script, meta, and css tags as children of the head, achieves nearly the same thing.

    Thanks to @duri for the workaround tip!