Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does IE give unexpected errors when setting innerHTML

I tried to set innerHTML on an element in firefox and it worked fine, tried it in IE and got unexpected errors with no obvious reason why.

For example if you try and set the innerHTML of a table to " hi from stu " it will fail, because the table must be followed by a sequence.

like image 515
stu Avatar asked Sep 30 '08 22:09

stu


People also ask

Why innerHTML does not work?

People can struggle and complain about innerHTML not working. Such things usually occur because of human error, when strings are not appropriately defined, or there are some mistakes in JavaScript code.

What is the disadvantage of innerHTML?

Disadvantages of innerHTMLIt is very slow because as inner HTML already parses the content even we have to parse the content again so that's why it takes time. When we have used the event handlers then the event handlers are not automatically attached to the new elements created by innerHTML.

Is setting innerHTML synchronous?

Setting innerHTML is synchronous, as are most changes you can make to the DOM. However, rendering the webpage is a different story. (Remember, DOM stands for "Document Object Model".


2 Answers

You're seeing that behaviour because innerHTML is read-only for table elements in IE. From MSDN's innerHTML Property documentation:

The property is read/write for all objects except the following, for which it is read-only: COL, COLGROUP, FRAMESET, HEAD, HTML, STYLE, TABLE, TBODY, TFOOT, THEAD, TITLE, TR.

like image 138
Jonny Buchanan Avatar answered Oct 21 '22 03:10

Jonny Buchanan


Don't know why you're being down-modded for the question Stu, as this is something I solved quite recently. The trick is to 'squirt' the HTML into a DOM element that is not currently attached to the document tree. Here's the code snippet that does it:

// removing the scripts to avoid any 'Permission Denied' errors in IE
var cleaned = html.replace(/<script(.|\s)*?\/script>/g, "");

// IE is stricter on malformed HTML injecting direct into DOM. By injecting into 
// an element that's not yet part of DOM it's more lenient and will clean it up.
if (jQuery.browser.msie)
{
    var tempElement = document.createElement("DIV");
    tempElement.innerHTML = cleaned;
    cleaned = tempElement.innerHTML;
    tempElement = null;
}
// now 'cleaned' is ready to use...

Note we're using only using jQuery in this snippet here to test for whether the browser is IE, there's no hard dependency on jQuery.

like image 23
Duncan Smart Avatar answered Oct 21 '22 05:10

Duncan Smart