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.
That kinda...sorta...makes sense (what IE is doing).
Okay, sure. Burn me now.