Home > Software design >  False "the node before which the new node is to be inserted is not a child of this node."
False "the node before which the new node is to be inserted is not a child of this node."

Time:09-13

None of the other related questions had a working answer, thus I decided to ask here myself.

While writing JavaScript I keep getting the following error no matter what I try:

Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node.

This is the line of code I have, after replacing variable names:

newElement.insertBefore(document.body, aChildOfDocumentBody);

Both newElement and aChildOfDocumentBody are defined with getElementById.

Even when I try newElement.insertBefore(document.body, document.body.children[0]) JavaScript says that the child doesn't belong to document.body. What am I doing wrong?

CodePudding user response:

This seems to be just a misordering of variables in your function call

newElement.insertBefore(document.body, document.body.children[0])

Should (I think) be

document.body.insertBefore(newElement, document.body.children[0]);

CodePudding user response:

I've found a solution and am writing this here for others:

You need to use .insertBefore on the parent!

So I was supposed to do document.body.insertBefore(newElement, ...)

If only this method had a docstring...

  • Related