Search code examples
phpdomdocument

Remove specific class domdocument


I have this in dom document:

<div><span class="hello"></span><div>

And I want to remove all spans with that class. So I tried:

$xpath = new DOMXPath($doc);
$elements = $xpath->query('//span[@class="hello"]/..');

foreach ($elements as $el) {
  $el->parentNode->removeChild($el);
}

But this removes the parent element as well (the div element). How can I only remove the span elements?


Solution

  • The /.. at the end of your XPath selector is selecting the parent element, not the <span> itself - .. means to work one level back up the tree, the same as in a directory path. So in your loop, where you say parentNode->removeChild, you're actually removing the div, since $el is already the span's parent element.

    If you just remove the /.. from the end of the selector, the code should work as intended.

    $xpath = new DOMXPath($doc);
    $elements = $xpath->query('//span[@class="hello"]');
    
    foreach ($elements as $el) {
        $el->parentNode->removeChild($el);
    }
    

    Full example: https://3v4l.org/o4dRv