Web DevelopmentremoveChild in IE8 doesn't set parentNode to null

Some people still have to write code that is supported in Internet Explorer 8, lucky you if you're not one of them. We all know that IE8 has issues, but here's one that was new to me until recently.

Suppose you call removeChild to remove an element from it's parent node, you may expect that element's parentNode to then be null. That's reasonable, and it seems IE9+, Firefox and Chrome all behave this way. But in IE8 it's not null! It's actually some random document fragment.

element.parentNode.removeChild(element);
element.parentNode == null; // false in IE8

What the...?!

So what can we do if we want to check if an element really has a parentNode? Well you may suspect that the document fragment is unique, but it seems as though every removed element has it's own document fragment assigned, so no joy there.

Probably the best you can do is to use element.parentElement instead. It's a DOM4 method but all the browsers support it (assuming element is itself an Element). By definition it will be null if the parent is not an element, so will bypass the problem of the IE8 document fragment.

It will obviously miss any cases of elements being intentionally appended directly to a document fragment, or the document itself (but that's just going to be the <html> element). I imagine it's sufficient for most use cases.

Here, try it yourself. If you can't dig up an old IE8 you can use the dev tools to put it in IE8 mode...

Feed reader? View this demo on the site.