jQuery throws SCRIPT5022: HierarchyRequestError when attempted to append a jQuery object on Internet Explorer ( IE)

后端 未结 1 994
难免孤独
难免孤独 2020-12-11 11:59

I\'m trying to use jQuery to insert an HTML table as a child node of a div element. My code looks something like this :

var table = $(\'#tableId\').clone();         


        
相关标签:
1条回答
  • 2020-12-11 12:15

    This seems to be an Internet Explorer security feature, you cannot append a DOM node or jQuery object from one window to another in Internet Explorer, even those meeting same origin criteria and in situations where it works in other browsers - nodes simply cannot be passed between the opened window and the opener.

    If you have a jQuery object then you can convert it to a DOM element and take the outerHTML as follows-

    var table = $('#tableId').clone(), tableHtml = table[0].outerHTML;
    

    Alternatively you could stick to plain JavaScript and write-

    var tableHtml = document.getElementById('tableId').outerHTML;
    

    This can then be added into the window document by setting the innerHTML of the desired DOM element as follows-

    $('#divId')[0].innerHTML = tableHtml ;
    

    or

    document.getElementById('divId').innerHTML = tableHtml;
    

    or

    document.querySelector('#divId').innerHTML = tableHtml;
    

    I have yet to see any actual documentation stating this, or giving the rationale behind it, but I have seen it cited in other StackOverflow questions and it is certainly consistent with behaviour I have seen when working with Internet Explorer.

    Hat tip to NoGray in your linked question.

    0 讨论(0)
提交回复
热议问题