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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…