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.
No, that doesn't make sense at all. According to the spec, removeChild() returns a reference to the removed child. You can then reuse it elsewhere in the document if you want to. Removing a child shouldn't alter its contents.