IE不支持'insertBefore'

Teq*_*eq1 7 javascript internet-explorer

我对这段代码有疑问:

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

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

在IE中我有一个错误:

SCRIPT438:Object不支持属性或方法'insertBefore'

有没有办法解决这个问题?

Dr.*_*lle 10

像这样使用它:

var parent=document.getElementById(parentID);
Run Code Online (Sandbox Code Playgroud)

否则父将是全局的,但总是有一个全局父对象,窗口(它是只读的).

此外: IE要求第二个参数为有效节点或null,因此请确保父节点具有childNodes以避免错误:

parent.insertBefore(child,(parent.hasChildNodes())
                            ? parent.childNodes[0]
                            : null);
Run Code Online (Sandbox Code Playgroud)

  • `(parent.hasChildNodes())?parent.childNodes [0]:null`可以缩短为`parent.childNodes [0] || null` (4认同)

DDM*_*DDM 5

insertBefore在正常工作IE,只要该第二参数是有效DOM元素,或nulltypeof nullObject,所以是一个typeofDOM元素)。

对于 an Array,任何越界索引(在本例中0children[]空)都将返回undefined。IE 在以下情况下停止工作,因为第二个参数变为undefined-

parent.insertBefore(child, parent.childNodes[0])
//parent.childNodes[INDEX]
//where `INDEX` is greater than parent.childNodes.length
Run Code Online (Sandbox Code Playgroud)

因此,对于这种情况,更好的方法是

var refEl  = parent.childNodes[INDEX] || null;
parent.insertBefore(newRowHolderNode.childNodes[0], refEl);
Run Code Online (Sandbox Code Playgroud)