I have this piece of code:
<textarea id="test" style="width: 400px; height: 100px"></textarea>
<script>
var inserting = document.createElement("div");
docume开发者_运维知识库nt.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?
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>
.insertBefore()
needs to be called on a DOM node. document
is not a DOM node. Try using the parent node of your textarea.
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 newElementparentElement
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(){
...
}
You want to add your node to document.body
not document
:
document.body.insertBefore(inserting, document.getElementById("test"));
精彩评论