Why does IE drop innerHTML / children of the DOM after modifying the DOM?

I tested the following code snippet for IE, Chrome, and Firefox and wondered what caused 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 0" 

Unsurprisingly, in three browsers, after the second innerHTML change, the divElement no longer refers to the displayed <div> . I have no problem with this.

What I find more interesting is that IE seems to drop the divElement . 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 wrapper.

What is the difference in how the browser handles the innerHTML change that causes this behavior?

+6
source share
1 answer

IE takes a different approach to the innerHTML property (compared to other browsers). Although the expected action would be to first remove the child nodes (keeping the links) and then install a new HTML fragment, IE actually seems to recursively destroy all the child nodes, leaving the links (e.g. divElement as an example) completely empty and non-functional. The innerText method has a similar effect.

The best explanation I received was on an MSDN post , claiming that in IE innerHTML is a DHTML (non-DOM) feature, as well as a low-level destructive method. I know that innerHTML was implemented before the W3 DOM specification (back during IE / Netscape browsers), but I don't know if this low-level behavior is some inherited implementation in IE.

However, W3 does not say that child nodes should be saved or destroyed (and this is a very recent recommendation by the candidate, innerHTML not part of the HTML4 specification ). Other references to W3 are also not definitive (at least none of them were found).

+2
source

Source: https://habr.com/ru/post/973445/


All Articles