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?
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With