How to delete element with DOMDocument? How to delete element with DOMDocument? php php

How to delete element with DOMDocument?


You remove the node by telling the parent node to remove the child:

$href->parentNode->removeChild($href);

See DOMNode::$parentNodeDocs and DOMNode::removeChild()Docs.

See as well:


This took me a while to figure out, so here's some clarification:

If you're deleting elements from within a loop (as in the OP's example), you need to loop backwards

$elements = $completePage->getElementsByTagName('a');for ($i = $elements->length; --$i >= 0; ) {  $href = $elements->item($i);  $href->parentNode->removeChild($href);}

DOMNodeList documentation: You can modify, and even delete, nodes from a DOMNodeList if you iterate backwards


Easily:

$href->parentNode->removeChild($href);