Is there a bug in Internet Explorer 9/10 with innerHTML=“”?

后端 未结 1 1406
-上瘾入骨i
-上瘾入骨i 2020-12-19 06:57

I often use the following code to clear the content of an element :

div.innerHTML = \"\";

But I found a stange behaviour on Internet Explor

1条回答
  •  鱼传尺愫
    2020-12-19 07:03

    That's very interesting behavior, and happens on IE8 and IE11 as well. Here's a rather simpler test/proof:

    var span = document.createElement('span');
    span.appendChild(document.createTextNode("This disappears on IE"));
    
    var div = document.createElement('div');
    div.appendChild(span);
    snippet.log("[before] span's childNodes.length: " + span.childNodes.length);
    div.innerHTML = "";
    snippet.log("[after] span's childNodes.length: " + span.childNodes.length);
    
    

    After setting the div's innerHTML to "", the span we kept a reference to loses its child text node on IE, and not on other browsers.

    We're not the only ones to notice this and find it, um, inappropriate.

    It doesn't have to be "", either, any new content causes the bug:

    var span = document.createElement('span');
    span.appendChild(document.createTextNode("This disappears on IE"));
    
    var div = document.createElement('div');
    div.appendChild(span);
    snippet.log("[before] span's childNodes.length: " + span.childNodes.length);
    div.innerHTML = "New content"; // <== Not ""
    snippet.log("[after] span's childNodes.length: " + span.childNodes.length);
    
    

    What little we have in the way of a spec for innerHTML is quite vague on what should happen to the old content, but surely this is wrong, even if Microsoft did invent innerHTML.

    Whereas removing the nodes via removeNode doesn't cause this behavior:

    var span = document.createElement('span');
    span.appendChild(document.createTextNode("This disappears on IE"));
    
    var div = document.createElement('div');
    div.appendChild(span);
    snippet.log("[before] span's childNodes.length: " + span.childNodes.length);
    while (div.firstChild) {
      div.removeChild(div.firstChild);
    }
    snippet.log("[after] span's childNodes.length: " + span.childNodes.length);
    
    

    sigh

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