<?php
$dom = Dom\HTMLDocument::createFromString('<!DOCTYPE HTML><html><p>hi</p> test <p>hi2</p></html>');
$dom->documentElement->replaceChildren('foo', $dom->createElement('p'), 'bar');
echo $dom->saveHtml();
?>
The above example will output:
<!DOCTYPE html><html>foo<p></p>bar</html>