I have a DOM looking like this:
div id = main
div
div
And i want to put the div called “middle” like this:
div id = main
div id = middle
div
div
So i want to move all child nodes of main node to the middle node and the middle node to become only child of main. I try to figure it out but i can’t.
I use this code:
$wrapper = $doc->createElement('div');
foreach($node->childNodes as $child)
{
$node->removeChild($child);
$wrapper->appendChild($child);
}
$node->appendChild($wrapper);
But it does not work.
And if i do:
$wrapper = $doc->createElement('div');
$children = $node->childNodes;
for($i = $children->length; $i--;) {
$child = $children->item($i);
$node->removeChild($child);
$wrapper->appendChild($child);
}
$node->appendChild($wrapper);
Items are moved, but in reverse order.
How to do this correctly in PHP?
1 Answer