Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete element with DOMDocument?

Is it possible to delete element from loaded DOM without creating a new one? For example something like this:

$dom = new DOMDocument('1.0', 'utf-8');
$dom->loadHTML($html);

foreach($dom->getElementsByTagName('a') as $href)
    if($href->nodeValue == 'First')
        //delete
like image 267
Kin Avatar asked Mar 07 '13 13:03

Kin


People also ask

How do you delete an element?

The remove() method removes an element (or node) from the document.

How do you delete an element in HTML?

Approach: Select the HTML element which need to remove. Use JavaScript remove() and removeChild() method to remove the element from the HTML document.

What is used to delete an HTML element from DOM?

remove() The Element. remove() method removes the element from the DOM.

What is removeChild in JavaScript?

The removeChild() method of the Node interface removes a child node from the DOM and returns the removed node. Note: As long as a reference is kept on the removed child, it still exists in memory, but is no longer part of the DOM. It can still be reused later in the code.


3 Answers

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:

  • How to remove attributes using PHP DOMDocument?
  • How to remove an HTML element using the DOMDocument class
like image 112
hakre Avatar answered Oct 08 '22 05:10

hakre


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

like image 22
alexanderbird Avatar answered Oct 08 '22 05:10

alexanderbird


Easily:

$href->parentNode->removeChild($href);
like image 22
silkfire Avatar answered Oct 08 '22 04:10

silkfire