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.
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.
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.
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".
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With