Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does IE discard the innerHTML/children of a DOM element after DOM changes?

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?

like image 248
Paul D. Avatar asked Aug 06 '14 18:08

Paul D.


1 Answers

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).

like image 103
Capilé Avatar answered Sep 28 '22 05:09

Capilé