As it was mentioned above, .insertBefore
works only with valid node (explicit ID or global document reference). Local variable reference would fail:
parent.insertBefore(child, localref); //error
In IE we can use .sourceIndex
property to get current global index of "marker" element, before which new child is inserted. Here is the fix for IE:
parent.insertBefore(child, document.all[localref.sourceIndex]);
It is not necessary to use .sourceIndex
property, if you know exactly where in parent tree you wish to insert an element. Following properties works just fine:
parent.insertBefore(child, parent.all[1]); //must be a child
parent.insertBefore(child, parent.children[2]); //any sane index
parent.insertBefore(child, parent.firstChild); //if at least one child exists
parent.insertBefore(child, parent.lastChild); //if at least one child exists
parent.insertBefore(child, localref.nextSibling]); //if not last child
parent.insertBefore(child, localref.previousSibling]); //if not first child