Jan Turoň
Jan Turoň

Reputation: 32912

document.insertBefore throws error

I have this piece of code:

  <textarea id="test" style="width: 400px; height: 100px"></textarea>
  <script>
    var inserting = document.createElement("div");
    document.insertBefore(inserting,document.getElementById("test"));
  </script>

Which should insert DIV id=inserting before textarea id=test, but this error occurs

Node was not found" code: "8

I use FireFox 3.6 with Firebug on WinXP. Where is the problem?

Upvotes: 5

Views: 9569

Answers (4)

jwueller
jwueller

Reputation: 30986

.insertBefore() needs to be called on a DOM node. document is not a DOM node. Try using the parent node of your textarea.

Upvotes: 4

lincolnk
lincolnk

Reputation: 11238

You want to add your node to document.body not document:

document.body.insertBefore(inserting, document.getElementById("test")); 

Upvotes: -1

Justin Ethier
Justin Ethier

Reputation: 134177

As others have mentioned, you need to call insertBefore on the parent of the <textarea> node. According to the API documentation for Node.insertBefore:

Summary

Inserts the specified node before a reference element as a child of the current node.

Syntax

var insertedElement = parentElement.insertBefore(newElement, referenceElement);

If referenceElement is null, newElement is inserted at the end of the list of child nodes.

  • insertedElement The node being inserted, that is newElement
  • parentElement The parent of the newly inserted node.
  • newElement The node to insert.
  • referenceElement The node before which newElement is inserted.

So you want to say something along the lines of:

parent_element_goes_here.insertBefore(inserting,document.getElementById("test"));

Instead of:

document.insertBefore(inserting,document.getElementById("test"));


Also, your code may be executing before the DOM has finished being loaded. You can ensure all of the DOM elements are loaded by using the window.onload event handler. From the MDC docs:

The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading.

So instead of calling your code directly, you would do this:

window.onload=function(){
    ...
}

Upvotes: 3

RoToRa
RoToRa

Reputation: 38420

insertBefore needs to called on the parent element of the element before which is inserted:

<textarea id="test" style="width: 400px; height: 100px"></textarea>
  <script>
    var inserting = document.createElement("div");
    var insertAt = document.getElementById("test");
    insertAt.parentNode.insertBefore(inserting,insertAt);
  </script>

Upvotes: 11

Related Questions