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?
That's very interesting behavior, and happens on IE8 and IE11 as well. Here's a rather simpler test/proof:
After setting the
div
'sinnerHTML
to""
, thespan
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: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 inventinnerHTML
.Whereas removing the nodes via
removeNode
doesn't cause this behavior:sigh