Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
475 views
in Technique[技术] by (71.8m points)

javascript - Is there a bug in Internet Explorer 9/10 with innerHTML=""?

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

div.innerHTML = "";

But I found a stange behaviour on Internet Explorer. It seems that all children of the div get their own children removed too! If I keep a reference to a child of the div above, after doing div.innerHTML = "";, the child's text node is no longer in the child.

The following code is the proof of this behaviour (http://jsfiddle.net/Laudp273/):

function createText() {
    var e = document.createElement("div");
    e.textContent = "Hello World!";
    return e;
}

var mrk = document.createElement("div");
mrk.appendChild(createText());
mrk.style.border = "4px solid yellow";

var container = null;

function addDiv() {
    if (container) {
        container.innerHTML = "";
    }
    var e = document.createElement("div");
    e.appendChild(mrk);
    container = e;
    document.body.appendChild(e);
}

var btn = document.createElement("button");
btn.textContent = "Add marker";
btn.addEventListener(
    "click",
    function() {
        addDiv();
    },
    false
);
document.body.appendChild(btn);

If you click on the "Add Marker" button twice, you will see an empty yellow rectangle instead of one with the texte "Hello wordl!".

Is this a bug or a specification not used by Firefox nor Google Chrome?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...