AvailabilityDOM Level 1 Core SynopsisNode insertBefore(Node newChild, Node refChild) throws DOMException; Arguments
ReturnsThe node that was inserted. ThrowsThis method may throw a DOMException with the following code values:
DescriptionThis method inserts the node newChild into the document tree as a child of this node. The new node is positioned within this node's childNodes[] array so that it comes immediately before the refChild node. If refChild is null, newChild is inserted at the end of childNodes[], just as with the appendChild( ) method. Note that it is illegal to call this method with a refChild that is not a child of this node. If newChild is already in the document tree, it is removed from the tree and then reinserted at its new position. If newChild is a DocumentFragment node, it is not inserted itself; instead, each of its children is inserted, in order, at the specified location. ExampleThe following function inserts a new paragraph at the beginning of a document: function insertMessage(message) { var paragraph = document.createElement("p"); // Create a <p> Element var text = document.createTextNode(message); // Create a Text node paragraph.appendChild(text); // Add text to the paragraph // Now insert the paragraph before the first child of the body document.body.insertBefore(paragraph, document.body.firstChild) } See AlsoNode.appendChild( ), Node.removeChild( ), Node.replaceChild( ) |