tags:

views:

48

answers:

4

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?

+1  A: 

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(){
    ...
}
Justin Ethier
your code doesn't work. delaying the script does nothing here because the dom is fine.
lincolnk
Thank you, the link you provided was very useful.
Jan Turoň
+2  A: 

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

elusive
+2  A: 

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>
RoToRa
Yes! I have successfully tested. Not document, neither document.body, but only parentNode can be the caller of insertBefore. Thank you, this was exactly what I was trying to figure out.
Jan Turoň
A: 

you want to add your node to document.body, not document.

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