Thursday, October 23, 2025
HomeLanguagesPHP | DOMNode insertBefore() Function

PHP | DOMNode insertBefore() Function

The DOMNode::insertBefore() function is an inbuilt function in PHP which is used to insert a new node before a certain another node.

Syntax:

DOMNode DOMNode::insertBefore( DOMNode $newNode, DOMNode $refNode )

Parameters:This function accepts two parameters as mentioned above and described below:

  • $newNode: It specifies the new node.
  • $refNode (Optional): It specifies the reference node. If not supplied, newnode is appended to the children.

Return Value: This function returns the inserted node.

Exceptions: This function throws DOM_NO_MODIFICATION_ALLOWED_ERR, if this node is readonly or if the previous parent of the node being inserted is readonly. DOM_HIERARCHY_REQUEST_ERR, if this node is of a type that does not allow children of the type of the $newNode node, or if the node to append is one of this node’s ancestors or this node itself, DOM_WRONG_DOCUMENT_ERR, if $newNode was created from a different document than the one that created this node, DOM_NOT_FOUND, if $refNode is not a child of this node.

Below given programs illustrate the DOMNode::insertBefore() function in PHP:

Program 1:




<?php
  
// Create a new DOMDocument
$dom = new DOMDocument();
  
// Create a paragraph element
$p_element = $dom->createElement('p', 
      'This is the paragraph element!');
  
// Append the child
$dom->appendChild($p_element);
  
// Create a paragraph element
$h_element = $dom->createElement('h1', 
      'This is the heading element!');
  
// Insert heading before HTML
$dom->insertBefore($h_element, $p_element);
  
// Render the output
echo $dom->saveXML();
?>


Output:

<?xml version="1.0"?>
<h1>This is the heading element!</h1>
<p>This is the paragraph element!</p>

Program 2:




<?php
  
// Create a new DOMDocument
$dom = new DOMDocument();
  
// Create a paragraph element
$p_element = $dom->createElement('p', 
      'neveropen, paragraph');
  
// Append the child
$dom->appendChild($p_element);
  
// Create a paragraph element
$h_element = $dom->createElement('h1',
      'neveropen, heading');
  
// When second argument is not provided
// It will appended to the child
$dom->insertBefore($h_element);
  
// Render the output
echo $dom->saveXML();
?>


Output:

<?xml version="1.0"?>
<p>neveropen, paragraph</p>
<h1>neveropen, heading</h1>

Reference: https://www.php.net/manual/en/domnode.insertbefore.php

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS