(PHP 8)
DOMElement::replaceWith — Replaces the element with new nodes
public DOMElement::replaceWith(DOMNode|string ...$nodes): void
Replaces the element with new nodes.
nodesThe replacement nodes. Strings are automatically converted to text nodes.
No value is returned.
DOM_HIERARCHY_REQUEST_ERR Raised if the parent is of a type that does not allow children of the type of one of the passed nodes, or if the node to put in is one of this node's ancestors or this node itself.
DOM_WRONG_DOCUMENT_ERR Raised if one of the passed nodes was created from a different document than the one that created this node.
| Version | Description |
|---|---|
| 8.3.0 | Calling this method on a node without a parent is now a no-op to align the behaviour with the DOM specification. Previously this threw a DOMException with code DOM_HIERARCHY_REQUEST_ERR. |
Example #1 DOMElement::replaceWith() example
Replaces the element with new nodes.
<?php
$doc = new DOMDocument;
$doc->loadXML("<container><hello/></container>");
$cdata = $doc->documentElement->firstChild;
$cdata->replaceWith("beautiful", $doc->createElement("world"));
echo $doc->saveXML();
?> The above example will output:
<?xml version="1.0"?> <container>beautiful<world/></container>
© 1997–2025 The PHP Documentation Group
Licensed under the Creative Commons Attribution License v3.0 or later.
https://www.php.net/manual/en/domelement.replacewith.php