Grauw’s blog

At Backbase, we just ran in to a very strange browser bug. In Internet Explorer, when creating an HTML element and then appending a child node to it, the element is placed in a document fragment node. In all other browsers the parentNode property stays null and according to the standard (and common sense), this should definitely not happen.

var oDiv = document.createElement('div');
oDiv.appendChild(document.createTextNode('xxx'));
alert('Parent node? ' + (oDiv.parentNode ? 'yes' : 'no'));

Expected result: “Parent node? no”

The workaround:

var oDiv = document.createElement('div');
oDiv.appendChild(document.createTextNode('xxx'));
if (oDiv.parentNode)
    oDiv.removeNode();
alert('Parent node? ' + (oDiv.parentNode ? 'yes' : 'no'));

Expected result: “Parent node? no”

This workaround uses the IE-only removeNode method to remove the element from its parent. Strangely enough, the standard DOM removeChild method can not be used to fix this issue. This fix only works as long as the node is detached; once it is attached to a node and then removed again, the issue reappears.

This bug happens in both quirks and standards mode, and is also still present in the Internet Explorer 8 beta 2 release.

Grauw

Comments

DocumentFragment and IE by Travis [MSFT] at 2008-10-23 20:14

From an “insider” perspective...

After the first line of your repro code (first button): var oDiv = document.createElement(‘div’);,
IE had created an “orphaned element”. As an implementation detail, all orphaned elements are automatically included in a Document (In IE DocumentFragment=Document). Thus you could immediately query the oDiv to see that it already had a document as its parentNode (you don’t need to add a child to it to get this behavior).

Just thought you’d like to know :)

-Travis

Re: DocumentFragment and IE by Grauw at 2008-10-23 23:51

Hey Travis,

Thanks for the response, always nice to hear about the innards of browsers :). Though the second line is necessary to reproduce this issue! My guess is that it was fixed at some time in the past, but not completely, or something.

IE by Anura Pand at 2015-11-03 10:22

It just goes to show that we still need to tend to Internet Explorer. Designers and Javascripters around the world blog a lot about killing IE, and ignore it in favor of modern browsers, but we can’t just toss it aside light-heartedly. Thanks for sharing