0

remove is failing with not found exception.

PHP Fatal error:  Uncaught DOMException: Not Found Error
$document = new \DOMDocument();
$raw = '
some text
<a href="sad" sometag="true">linkkkk</a>
more text
';
$document->loadHTML($raw);

$links = $document->getElementsByTagName('a');
$a = $links->item(0);

$document->removeChild($a);

2 Answers 2

1

You could remove it from the parentNode from $a

$document = new \DOMDocument();
$raw = '
some text
<a href="sad" sometag="true">linkkkk</a>
more text
';
$document->loadHTML($raw);

$links = $document->getElementsByTagName('a');
$a = $links->item(0);
$a->parentNode->removeChild($a);
Sign up to request clarification or add additional context in comments.

Comments

0

getElementsByTagName() returns a list of any descendant element node a. So $links is not the parent node.

With PHP > 8.0 you can use the method DOMNode::remove():

$links = $document->getElementsByTagName('a');
$a = $links->item(0);
$a->remove();

Or use the parentNode property:

$links = $document->getElementsByTagName('a');
$a = $links->item(0);
$a->parentNode->removeChild($a);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.