I tested the following piece of code against IE, Chrome and Firefox and was wondering what causes the differences in the results.
var body = document.getElementsByTagName('body')[0];
body.innerHTML = '<div id="myId"><span>I am a text</span></div>';
var divElement = document.getElementById('myId');
console.log(divElement.children.length);
// All browsers say "1" !
body.innerHTML = ''; // just resetting the DOM
console.log(divElement.children.length);
// Chrome and FF say "1", IE says "Sorry guys, it's 0"
Without surprise, in the three browsers, after the second innerHTML
change, the divElement
object does not refer to the rendered <div>
anymore. I have no trouble with that.
What I find more interesting is that IE seem to discard divElement
's child. Chrome and FF still allow me to work with the old tag and its children as if they were rendered, but IE turned the tag into an empty shell.
What could be the difference in the way the browsers process the innerHTML
change that causes this behavior?
IE adopts a different approach to innerHTML
property (compared to other browsers). While the expected action would be to remove the child nodes first (preserving references), then set the new HTML fragment, IE actually seems to recursively destroy all child nodes, leaving the references (like divElement
in the example) completely empty and non-functional. The innerText
method has a similar effect.
The best explanation I got was at a MSDN post claiming that in IE, innerHTML
is a DHTML (not DOM) characteristic and also a low-level destructive method. I know that innerHTML
was implemented before W3 DOM specification (back at IE/Netscape browser wars), but don't know if this low-level behavior is some legacy implementation in IE.
Still, W3 doesn't say that the child nodes should be preserved or destroyed (and it's a very recent Candidate Recommendation, innerHTML
was not part of HTML4 specification). Other references at W3 are also not conclusive (at least none that I've found).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With