Why does IE give unexpected errors when setting innerHTML

后端 未结 10 2794
面向向阳花
面向向阳花 2020-12-10 17:20

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

10条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-10 18:08

    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(//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.

提交回复
热议问题