What do you think this will output?
var div = document.createElement('div');
div.innerHTML = '<span>Hello world!</span>';
var span = div.firstChild;
div.innerHTML = '<span>Uh oh!</span>';
console.log(span.innerHTML);
Go on, have a guess.
…
…
…
Ok, here's what happens:
According to the spec, setting innerHTML
removes all children from the node (as if you called removeChild
on each). The span we pulled out is detached, but otherwise unmodified, so "Hello world!" is logged. This is what Chrome, Firefox & Opera do.
IE has done this differently for as long as I can remember (and still does in IE10). Setting innerHTML
removes all descendants from their parents, so we still have a reference to a span, but it's empty, so "" is logged.
Given that innerHTML started life as an IE-only feature back in IE4, it could be argued that whatever IE does is, by definition, the correct behaviour, and that therefore the spec and the other browsers are wrong.