Search Results
DOMNode::insertBefore (PHP 5, PHP 7, PHP 8) DOMNode::insertBefore — Adds a new child before a reference node
Mar 5, 2020 · Your All-in-One Learning Portal: GeeksforGeeks is a comprehensive educational platform that empowers learners across domains-spanning computer science and programming, school education, upskilling, commerce, software tools, competitive exams, and more.
- Overview
- Syntax
- Example
- Browser compatibility
- See also
The insertBefore() method of the Node interface inserts a node before a reference node as a child of a specified parent node.
If the given node already exists in the document, insertBefore() moves it from its current position to the new position. (That is, it will automatically be removed from its existing parent before appending it to the specified new parent.)
This means that a node cannot be in two locations of the document simultaneously.
If the given child is a DocumentFragment, the entire contents of the DocumentFragment are moved into the child list of the specified parent node.
Parameters
newNode The node to be inserted. referenceNode The node before which newNode is inserted. If this is null, then newNode is inserted at the end of node's child nodes.
Return value
Returns the added child (unless newNode is a DocumentFragment, in which case the empty DocumentFragment is returned).
Exceptions
Pre-insert validity
Example 1 Example 2
Note: There is no insertAfter() method. It can be emulated by combining the insertBefore method with Node.nextSibling. In the previous example, sp1 could be inserted after sp2 using:If sp2 does not have a next sibling, then it must be the last child — sp2.nextSibling returns null, and sp1 is inserted at the end of the child node list (immediately after sp2).
Example 3
Insert an element before the first child element, using the firstChild property.When the element does not have a first child, then firstChild is null. The element is still appended to the parent, after the last child. Since the parent element did not have a first child, it did not have a last child, either. Consequently, the newly inserted element is the only element.
BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
•Node.removeChild()
•Node.replaceChild()
•Node.appendChild()
•Node.hasChildNodes()
•Element.insertAdjacentElement()
•Element.prepend()
DOMNode::insertBefore 26 déc. 2018 21 fois (PHP 5, PHP 7, PHP 8)
The trick to using this method is that the OBJECT on which you actually CALL the insertBefore () method is actually the PARENT node of the reference node!
This function inserts a new node right before the reference node. If you plan to do further modifications on the appended child you must use the returned node.
This function inserts a new node right before the reference node. If you plan to do further modifications on the appended child you must use the returned node.
