php8.5
Home/ Manual/ dom / domelement/ DOMElement::insertAdjacentElement

DOMElement::insertAdjacentElement

PHP function Edit on GitHub ✎

(PHP 8 >= 8.3.0)

Insert adjacent element

Description

DOMElement::insertAdjacentElement(string $where, DOMElement $element): DOMElement|null

Inserts an element at a relative position given by where.

Parameters

where
  • beforebegin - Insert before the target element.
  • afterbegin - Insert as the first child of the target element.
  • beforeend - Insert as the last child of the target element.
  • afterend - Insert after the target element.
element

The element to insert.

Return Values

Return DOMElement or null on failure.

Examples

DOMElement::insertAdjacentElement example

php
<?php

$dom = new DOMDocument();
$dom->loadXML('<?xml version="1.0"?><container><p>foo</p></container>');
$container = $dom->documentElement;
$p = $container->firstElementChild;

$p->insertAdjacentElement('beforebegin', $dom->createElement('A'));
echo $dom->saveXML();
?>

The above example will output:

output
<?xml version="1.0"?>
<container><A/><p>foo</p></container>

See Also

  • DOMElement::insertAdjacentText

Source: reference/dom/domelement/insertadjacentelement.xml · from the official PHP manual (php/doc-en)