Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IE doesn't support 'insertBefore'

I have a problem with this piece of code :

    var logo = document.getElementById("move_this");
    prependElement('container', logo);

    function prependElement(parentID, child) {
        parent = document.getElementById(parentID);
        parent.insertBefore(child, parent.childNodes[0]);
    }

In IE I have an error:

SCRIPT438: Object doesn't support property or method 'insertBefore'

Is there a way to resolve this problem?

like image 959
Teq1 Avatar asked Feb 21 '12 12:02

Teq1


2 Answers

Use it like that:

var parent=document.getElementById(parentID);

otherwise parent will be global, but there always is a global parent-object, the parent window(and it is read-only).

Furthermore: IE requires as 2nd argument a valid node or null, so be sure that parent has childNodes to avoid errors:

parent.insertBefore(child,(parent.hasChildNodes())
                            ? parent.childNodes[0]
                            : null);
like image 158
Dr.Molle Avatar answered Sep 23 '22 06:09

Dr.Molle


insertBefore works correctly in IE as long as the 2nd parameter is a valid DOM element, or null ( typeof null is Object and so is a typeof DOM element).

For an Array, any out of bound index (which in this case is 0 as the children[] is empty) will return undefined. IE stops working in the following case as the 2nd param becomes undefined -

parent.insertBefore(child, parent.childNodes[0])
//parent.childNodes[INDEX]
//where `INDEX` is greater than parent.childNodes.length

So, a better approach for this case will be

var refEl  = parent.childNodes[INDEX] || null;
parent.insertBefore(newRowHolderNode.childNodes[0], refEl);
like image 25
DDM Avatar answered Sep 23 '22 06:09

DDM