Art Of Programming

musings by Dmytrii Nagirniak

Use insertBefore Instead of appendChild

You can get lots of problems when using node.appendChild due to an element may not be allowed to have children. It is especially valid for WYSIWYG editors.
To overcome this just use node.insertBefore which will always succeeds (it seems so at least). It is so just just because of insertBefore add a child to a parent, which already has at least one child and thus is can have children.
Also keeping in mind this constraint:
existingChild.insertBefore(newChild, null/*Feeding FF*/);
Assert.areSame(existingChild.parentNode, newChild.parentNode, "children should have the same parent");
Assert.areSame(root, existingchild.parentNode, "[root] should be a parent of [exitingChild]")
We can rewrite our code like:
* root-|
*      |->existingChild-|-newChild


existingChild.insertBefore(newChild, null);

This is especially useful when you have no idea what existingChild or root can be (as it is in WYSYWYG HTML editors) and seems to be much better and exactly what users need.